// Isetta Microcode
//
// version 251203

// 240419 Milestone: runs Apple 1 basic, with Raspberry Pi as console !
// 240615 runs ZX Spectrum Manic Miner (with patches, no sound yet).
// 240621 runs ZX Spectrum Manic Miner with sound (but patches in MM needed)
// 240622 added LDI instruction. 15+2 cycles.
// 240623 added RRD instruction. 13+2 cycles. The Great Escape running now.
// 240916 New LDIR instruction. Also Added LDDR, CPI, CPD.
// 241007 New instructions for interrupt handling
// 241122 Starting Blitter
// 241204 Stable version with mouse support (used for BOOT.BIN version 241221)
// 250220 Several things solved. Backup.
// 250307 Backup on email.
// 250319 New bankswitching port, #1B, for symbos-Isetta version 250319.
// 250326A Seems copycnv now working ok, for aligned and unaligned.
// 250403 SD card function working
// 250521 Starting sound generator
// 250624 Changing SHR shift-right table position


//
// https://www.piliapp.com/javascript-validator/   Use this for checking Javascript.


const generate_6502      = 1;
const generate_Z80       = 1;
const generate_undefined = 0;
const generate_blitter   = 1;


// get today's date. from:
// https://bugfender.com/blog/javascript-date-and-time/
const date = new Date();
const thisday = date.getDate();
const thismonth = date.getMonth() + 1; // The month index starts from 0
const thisyear = date.getFullYear();


const thisdate = `${thisday}/${thismonth}/${thisyear}`;

// for embedding in the microcode, convert to BCD
// https://stackoverflow.com/questions/65128269/how-to-convert-bcd-to-decimal-and-vice-versa
dec2bcd = dec => parseInt(dec.toString(10), 16);

// Isetta 6502/Z80 microcode by Roelh

const ISA_6502 = 0x38;
const ISA_Z80 = 0x39;  // values up to 0x3a can be defined (total 8 processors) in page 0
const ISA_BLIT = 0x3a; // 24-11-2024 blitter, used to return from interrupt
const ISA_PSG = 0x3b;   // 19-5-2025 programmable sound generator 

// 7-6-2023 switch interrupts on or off, to find where the problem is
/*
var int_enabled=0; 

function int_on()  { int_enabled = 1; }
function int_off()  { int_enabled = 0; }
*/

var listing_on = 1;

var short_download = 0; // short=1: only E000-E07D. short=0: full range E000 - EFFF

// Tab distance: 4 spaces

/*
function commentline(str) {
	//console.log(str);

	document.getElementById("microcode_area").innerHTML += str + "\n";

	//document.getElementById("demo").innerHTML += str + "<br>";
}
*/

// 15-8-2025 new commentline function, should be faster

var thelisting ="";

function commentline(str) {
	thelisting += str + "\n";
}

function commentline_init()
  { thelisting =""; }

function commentline_end()
  {	document.getElementById("microcode_area").innerHTML = thelisting + "\n";
  }




function error_msg(str) {
	commentline("********* ERROR: " + str + " *********");
	error_m_count++;
}

function hexstring6(input) {
	var hex = input.toString(16).toUpperCase();
	if (hex.length == 6) { return hex; }
	else if (hex.length == 5) { return "0" + hex; }
	else if (hex.length == 4) { return "00" + hex; }
	else if (hex.length == 3) { return "000" + hex; }
	else if (hex.length == 2) { return "0000" + hex; }
	return hex.length == 1 ? "00000" + hex : hex;
};

function hexstring2(input) {
	var hex = input.toString(16).toUpperCase();
	if (hex.length == 2) { return hex; }
	return hex.length == 1 ? "0" + hex : hex;
};

var compnr = 257;
const comp_name = [];
const comp_val = [];

function comp(val, name) {
	compnr++;
	comp_name[compnr] = name;
	comp_val[compnr] = val;
	return compnr;
}


function list_registers()  // 28-2-2026 
 { var i;
   var name;
   var val;
   i = first_reg;
   while (i <= last_real_reg)
     {  name = comp_name[i];
	    val = comp_val[i];	   
		if ( (val & 0x000300) == 0x000200) // 28-2-2026  is it a register ?
		{ // this will give: db 0x56,"reg_kb_bitbuf",0
		     name = name + "           ";
             name = name.substring(0, 12); // max 12 chars

			commentline(" db 0x" + hexstring2(val & 0xFF) + ',"' + name + '",0'  );
		}
		i++;
	 }
 }

// variables for the disassembler
var current_opcode = 0;
var current_page = 0;
var dis_data_name = [];
var dis_data_dst = [];
var dis_data_src = [];
var dis_data_bytes = [];
var dis_data_cycles = [];

// microcode generation options

//const option_z80_align_sp = 1;  Aligned SP doesn't work with Altair Basic. Don't use this.
const option_z80_align_sp = 0; // non-aligned, Altair Basic likes this.

/*
Altair 4k basic: 4kbas32 downloaded from https://schorn.ch/altair_3.php
Converted to binary: http://tomeko.net/online_tools/file_to_hex.php?lang=en
Explanation here: http://altairbasic.org/
*/

// The microcode is 24-bits wide:
//
//    --upper- -middle- --lower-
//    76543210 76543210 76543210
//
// The bits are described here: 
// https://hackaday.io/project/190345-isetta-ttl-computer/log/239102-programming-manual-microcode-and-blitter
//

// If we regard microcode as software, the following constants are
// really the link between the hardware and the software:

// microcode pages

const page_reset = comp(0x000000, 'p_reset');
const page_z80_ed = comp(0x000000, 'p_z80_ed');

// 3-2-2024
const page_6502 = comp(0x020000, 'p_6502');
const page_z80 = comp(0x040000, 'p_z80');
const page_z80_ix = comp(0x060000, 'p_z80_ix');
const page_in = comp(0x060000, 'p_in'); // 5-3-2024 same as page_z80_ix
const page_rtc = comp(0x140000, 'p_rtc'); // 9-8-2025 page24  12-8 later same as page_z80_ix (then also change page_nr below)
											// 15-8-2025  rtc on page_hires
const page_z80_cb = comp(0x080000, 'p_z80_cb');
const page_z80_iy = comp(0x0A0000, 'p_z80_iy');
const page_out = comp(0x0A0000, 'p_out');  // 5-3-2024 same as page_z80_iy
const page_download = comp(0x0C0000, 'p_download');
const page_download2 = comp(0x0E0000, 'p_download2');

const page_zx_video = comp(0x100000, 'p_zx_video'); // 6-6-2024  ZX spectrum video // 16-11-2024 changed page from 0x14.. to 0x10..

const page_cp_u = comp(0x110000, 'p_cp_u');  // 9-4-2025 table for copy-unaligned

const page_copycnv = comp(0x120000, 'p_copycnv'); // 19-3-2025  page18
const page_copycnv_un = comp(0x130000, 'p_copycnv_un'); // 19-3-2025  page19

const page_hires    = comp(0x140000, 'p_hires'); // 16-11-2024  Hires video

const page_sound      = comp(0x160000, 'p_sound'); // 20-5-2025  sound, page 22

const page_download3  = comp(0x180000, 'p_download3'); // 22-9-2025  page 24

const page_first = page_reset;

const page_last = page_sound;    // 20-5-2025

var page_nr = [];
// 29-5-2023 new page numbering
// main pages are 0, 2, 4, 6, 8, 10, 12, 14 .. 30   (16 cycles per opcode)
// odd numbered pages are 8 cycles 'above' the even pages.
// So odd numbered pages have max 8 cycles.
//
page_nr[page_reset] = 0; // same page as z80_ed
page_nr[page_z80_ed] = 0;
page_nr[page_6502] = 2;
page_nr[page_z80] = 4; // has no page 5
page_nr[page_z80_ix] = 6; // has no page 7
page_nr[page_z80_cb] = 8; // page 9 fully available
page_nr[page_z80_iy] = 10; // 20-7-2023

page_nr[page_download]   = 12; //  6-3-2024
page_nr[page_download2]  = 14; //  6-3-2024

page_nr[page_zx_video]   = 16; //  6-6-2024 // 16-11-2024 changed from 20 to 16
page_nr[page_cp_u]   = 17; // 9-4-2025

page_nr[page_copycnv]    = 18; //  19-3-2025
page_nr[page_copycnv_un] = 19; // 19-3-2025

page_nr[page_hires] = 20; //  16-6-2024 new

page_nr[page_sound] = 22; //  20-5-2025 new
page_nr[page_download3]  = 24; // 22-9-2025

page_nr[page_rtc] = 20; // 6; //  9-8-2025 new  15-8-2025 page_hires

// 5-3-2024

page_nr[page_in] = page_nr[page_z80_ix];
page_nr[page_out] = page_nr[page_z80_iy];


// memory banks

// there are 8 banks of 64kBytes

const bank0 = comp(0x000000, 'bank0'); // 7-9-2023
const bank1 = comp(0x000010, 'bank1'); // 7-9-2023  ctl_reg2=1
const bank2 = comp(0x000020, 'bank2'); // 7-9-2023  ctl_reg3=1
const bank3 = comp(0x000030, 'bank3'); // 7-9-2023  ctl_reg3=1 and ctl_reg2=1
const bank4 = comp(0x000040, 'bank4'); // 12-5-2024
const bank5 = comp(0x000050, 'bank5'); // 12-5-2024
const bank6 = comp(0x000060, 'bank6'); // 12-5-2024
const bank7 = comp(0x000070, 'bank7'); // 12-5-2024

const nop = comp(0x000000, 'nop');

// I/O port definitions

	// The register ports start at 0x10 up to 0x1F (skipping 0x19), in page_in and page_out (so not in page_reset)
	// The register ports enable reading and/or writing to/from a memory-resident register.
	// Other ports at 0x30 up to 0x3F skipping 0x34, 0x35, 0x36 and 0x39

	const port_out_isa_6502 = 0x0A;
	const port_out_isa_Z80  = 0x0B;	

	const port_io_reg_isa = 0x10;
	const port_io_reg_vga_ptl  = 0x11  // 29-4-2024
	const port_io_reg_vga_pth  = 0x12  // 29-4-2024
	const port_io_reg_vga_base = 0x13  // 29-4-2024
	//const port_out_sw_wr_sound_n= 0x14; //  4-2-2026 write CY to irq_ack/ (wr_sound/)	not used

	const port_in_gen_input  = 0x14  // 29-5-2024 read general parallel input port

	const port_out_sw_kb_send = 0x14; // set this i/o switch bit equal to CY ( not used )
	const port_out_sw_exx     = 0x15;
	
	const port_out_sw_vdu_n     = 0x16; // 27-11-2024
	const port_out_setup        = 0x17; // 27-11-2024,	8-12-2024 renamed to setup
	const port_out_system       = 0x18; // 21-12-2024 default 0, set system specifics
	const port_out_dbg          = 0x1A; // 11-1-2025 default 0, debug on/off
	const port_out_shutdn       = 0x1C; // 30-6-2025

	const port_in_config        =   0xE4  ;	// this tells what the HW configuration is. Default zero.
	const port_in_microcode_year =  0xE6  ; // 2-10-2024
	const port_in_microcode_month = 0xE7  ;
	const port_in_microcode_day =   0xE8  ;	

	const port_io_bank0 = 0xF0  // 16-11-2024
	const port_io_bank1 = 0xF1  // 12-5-2024	
	const port_io_bank2 = 0xF2  // 12-5-2024		
	const port_io_bank3 = 0xF3  // 12-5-2024	
	const port_io_bank4 = 0xF4  // 12-5-2024	
	const port_io_bank5 = 0xF5  // 12-5-2024	
	const port_io_bank6 = 0xF6  // 12-5-2024	
	const port_io_bank7 = 0xF7  // 12-5-2024	

	const port_out_sbnk   = 0x1B  // 18-3-2025 set symbos bank number	(bankswitching)
	const port_out_sbnkjp = 0x1E  // 18-11-2025 set symbos bank number and jump	(bankswitching)

	const port_out_wbnk   = 0x4A  // 26-11-2025
	const port_in_rbt     = 0x2F  
	const port_out_wbt    = 0x2F

	const port_in_bnk1_free = 0x27; // 30-6-2025 MSB of the first free 256-byte section in HW bank 1.

	const port_out_sound = 0x30;
	const port_in_scancode = 0x31;
	const port_out_tx = 0x31;
	const port_in_mouse = 0x32;	// 27-11-2024
	const port_out_sound_imm = 0x3A;// 11-12-2024	

	// 22-10-2024 new SPI functions
	const port_spi1_start = 0x32;  // needs 2 slots
	const port_spi2_start = 0x33;  // needs 2 slots
	const port_spi_out  = 0x37;  // 1 slot
	const port_spi_in   = 0x3A;  // needs 4 instruction slots !
	const port_spi2_out = 0x3B;  //	6-4-2025
	const port_spi2_in  = 0x37;  // 3-4-2025 read bit before clock pulse
	const port_spi2_in_fast  = 0x47;  // 11-5-2025 also does inc HL and ld (HL),A
	const port_spi_idle = 0x3F;  // 1 slot	
	const port_spi_state= 0x3C;  // 10-2-2025
	const port_spi_out_bit = 0x3D;  // 2 slot	30-3-2025
	const port_spi_in_bit =0x3E; // 1 slot 303-2025	 

    // PSG AY-3-8910  14-5-2025 Sound generator
	const port_out_psg_reg  = 0x40; // output, PSG register select. registers 0x00 - 0x0D (PSG default clk 1 MHz)
	const port_out_psg_data = 0x41; // output

	const port_out_sound_mode = 0x43; // output. with A=1, select zx-spectrum sound

    // specific for ZX Spectrum
	const port_io_zx_spectrum = 0xFE  // 7-6-2024	
	const port_io_zx_joystick = 0x1F  // 15-6-2024	

	// rtc
	const port_io_rtc_read  = 0xCC // in input page
	const port_io_rtc_write = 0xCC // in output page	
	//const rtc_tick  = 0x48
	//const rtc_tick2 = 0x4A
	const rtc_tick  = 0x23 // 27-9-2025
	const rtc_tick2 = 0x25	
	const rtc_shutdn = 0x18  // 23-9-2025
	const rtc_exit = 0x0     // 23-9-2025


	// reserve FD for spectrum-sound AY-3-8910: 

	// 17-11-2024 output ports for blitter parameters

	const p_dst_x_l = 0xa0;	  // destination (screen)  (A0 - A3 MSX PSG)
	const p_dst_x_h = 0xa1;	
	const p_dst_y_l = 0xa2;	
	const p_dst_y_h = 0xa3;
	const p_src_x_l = 0x90;	  // source
	const p_src_x_h = 0x91;	
	const p_src_y_l = 0x92;	
	const p_src_y_h = 0x93;	
	const p_src_a_l = 0x97;	  // source addr   ( 98 - 9B MSX VDP)
	const p_src_a_h = 0x98;	
	const p_src_a_u = 0x9a;
	const p_src_l_l = 0x9b;	  // source line length
	const p_src_l_h = 0x9f;				
	const p_size_x_l = 0xb0;	  // area size
	const p_size_x_h = 0xb1;	
	const p_size_y_l = 0xb2;	
	const p_size_y_h = 0xb3;	
	const p_fill_1 =  0x78;  // fill	
	const p_fill_2 =  0x79;		

	// 30-6-2025 to fit-in MSX ports, use the new blitter ports:

	const p_dst_x_l_new = 0x88;	  // destination (screen)  (was A0 - A3 MSX PSG)
	const p_dst_x_h_new = 0x89;	
	const p_dst_y_l_new = 0x8A;	
	const p_dst_y_h_new = 0x8B;

	const p_src_a_l_new = 0xB7;	  // source addr   ( was (97) 98 - 9B MSX VDP)
	const p_src_a_h_new = 0xB8;	
	const p_src_a_u_new = 0xB9;
	const p_src_l_l_new = 0xBA;	  // source line length
	const p_src_l_h_new = 0xBB;		

	const port_blitter = 0xea; // 22-11-2024 main blitter output port
							

// I/O ports reserved for MSX:  (30-6-2025)
// A0 - A3  PSG (collide with blitter)
// A8 - BB  8255 PPI (coll wit xorz)
// 98 - 9B  VDP (collide with blitter, xorz)


// RAM Memory use

//*********** Bank arrangement **************

// This is the new arrangement for pcb ISA2442

// 14-11-2024 Note that these are Physical banknumbers (address lines A18, A17, A16)

// Bank0
// Bank0   0000 - 00FF  All registers will go in this section (pcb ISA2442)
// Bank0   0100 - 01FF  27-11-2024  Mouse buffer
// Bank0   0200 - 02FF  TX output buffer, 30-6-2025
// Bank0   0300 - 04FF  Video pointer LSB (512 entries reserved). After the video, ZX sound samples are stored in this buffer:
// Bank0   0480         sound samples for ZX spectrum (141 of them)  ?? will this stay ?
//         050E - 0511  Storage for undefined instruction handler. 2 bytes magic nr, 2 bytes PC.
// Bank0   0520 - 053F  Channel control blocks, Sound   (  8 channels )  20-2-2025  (4 bytes per channel. but in 3 banks, so 12 bytes/channel)
//         0540 - 057F  free
// Bank0   0580 - 05FF  Channel control blocks, Sprites ( 32 channels )

// Bank0   0800 - 08FF  color translation table FG (zx spectrum)
// Bank0   0600 - FFFF  reserved for video data


// Bank1
// Bank1   0000 - 03FF  Reserved for SymbOS (august 2025)
// Bank1   0000 - 00FF  Table for right-shift (25-6-2025 Moving this to bank2) (30-6-2025 also moved for blitter. 6502 todo)
// Bank1   0100 - 01FF  
// Bank1   0200 - 02FF  
// Bank1   0300 - 050D  Video frame instruction table (525 entries) (this is moved to 700)
// Bank1   0300 - 0491  Color attribute MSB table (ZX Spectrum) new here 30-8-2025 (zero position + 400 lines)
// Bank1   04F0         SymbOS Language setting, written here by SymbOS 
// Bank1   04F1 - 04F6  ps/2 Keyboard language ID, (6-char code) Written by SymbOS.

// Bank1   0500 - 050F  RTC time values  8-8-2025

// Bank1   0520 - 053F  Channel control blocks, Sound   (  8 channels )
//         0540 - 057F  free
// Bank1   0580 - 05FF  Channel control blocks, Sprites ( 32 channels )

// Bank1   0600 - 08FF  Color attribute MSB table (ZX Spectrum), moved to 300 (30-8-2025)
// Bank1   0700 - 090D  Video frame instruction table (525 entries) New position, for SymbOs. 13-5-2025

// Bank1   0900 - 09FF  Copy of registers, after undefined instruction
// Bank1   0A00 - 0AFF  Symbos color conversion. First 16 filled by the Symbos Loader.
// Bank1   0C00         1K sound buffer A  13-5-2025
// Bank1   1000         1K sound buffer B  13-5-2025
// Bank1   1400         1K sound buffer C  13-5-2025
// Bank1   1800 - 1BFF  1K sound buffer D  13-5-2025
// Bank1   1C00 - 1C20  sound buffer overflow area
// Bank1   1C20 - 1FFF  free
// Bank1   2000 - 20FF  keyboard buffer, 30-6-2025

// Bank1   4000 - 57FF  ZX spectrum video end-of-line flags (last one at 5800)


// Bank2 
// Bank2   0000 - 00FF  Table for identity
// Bank2   0100 - 01FF  24-6-2025 new SHR table
// Bank2   0200 - 02FF  Nibble swap table. Must be filled by application, used by RRD
// Bank2   0300 - 04FF  Video pointer MSB (512 entries reserved)

// Bank2   0500 - 050F  Color conversion, 16 color to 64 color (for C64) <-- no longer
// Bank2   0500 - 050F  PSG amplitude conversion, (volume table) 1-6-2025
//        
// Bank2   0520 - 053F  Channel control blocks, Sound   (  8 channels )
//         0540 - 057F  free
// Bank2   0580 - 05FF  Channel control blocks, Sprites ( 32 channels )

// Bank2   0800 - 08FF  color translation table BG (zx spectrum)
// Bank2   0600 - FFFF  reserved for video data


// Bank3  
// Bank3   64kB for user program, directly visible by processor
// Bank3   4000 - 57FF  ZX spectrum video bitmap
// Bank3   5800 - 5AFF  ZX spectrum video color attributes
// Bank3   F700 - F7FF  Operating system default file buffer (not any more)
// Bank3   F800 - FFFF  Font 8x8  (not any more)


// Bank4, bank5, bank6, bank7: No specific data.


// RTC Time values, starting at 0x0500 in bank 1   8-8-2025

const time_msb = 5
const time_bnk = bank1;

// the next constants are the LSB of the RTC variables
const time_frac_l = 0;  // starts here. each frame, 11 must be added, and a 1/60 is generated.
					  // Halfway each frame, if fraction above limit, 59 * 21 (??) is subtracted and 
					  // one extra 1/60 generated
const time_frac_h = 1;					  
const time_60s  = 2;   // counts to 60
const time_secs = 3;   // counts to 60
const time_mins = 4;   // to 60
const time_hours= 5;   // to 24
const time_days = 6;   // to 28, 29, 30 or 31
const time_months=7;   // to 12
const time_years =8;   // to 256  (low byte of year)
const time_years256=9;  // (high byte of year)



//**********  Definition of microcode bit patterns  **********/

// Conditions

// 6-2-2024  removed the awkward upd_f
const upd_f = comp(0x000000, 'upd_f'); // 30-11-2023

const ctl_640 = comp(0x000400, 'ctl_640'); // 15-9-2025 select 640 pixel mode in video output. HW signal: upd_ctl_n
const ld_640  = comp(0x010400, 'ld_640'); // 15-9-2025 select 640 pixel mode in combination with "ld"


const l_to_f = comp(0x000800, 'l_to_f');
const first_cond = l_to_f; // 11-11-2023 for debugger

const h_to_f = comp(0x200800, 'h_to_f'); // h_to_f can only be used with group1 instructions
const c_to_f = comp(0x400800, 'c_to_f');
const tc_to_f = comp(0x600800, 'tc_to_f');
const n_to_f = comp(0x800800, 'n_to_f');
const r0_to_f = comp(0xA00800, 'r0_to_f');
const cond_r0 = comp(0xA00000, 'cond_r0'); // 24-6-2025 new shr
//const miso_to_f = comp(0xA00800, 'miso_to_f'); // 3-11-2024 same as r0_to_f but for group1 instructions

const dtc_to_f = comp(0xC00800, 'dtc_to_f'); // 16-10-2023

const irq_to_f = comp(0xE00800, 'irq_to_f');  // new here 7-11-2023.

const last_cond = irq_to_f; // 11-11-2023 for debugger

const z_to_f = comp(0xFFFF00, 'z_to_f'); // 22-7-2023 0xA00000 now used for SHR



// Destinations

const to_t   = comp(0x000000, 'to_t');
const to_dph = comp(0x001000, 'to_dph');
const to_bnk = comp(0x001080, 'to_bnk');  // 30-10-2024 to_bnk  (also writes to DPH)
const to_dpl = comp(0x002000, 'to_dpl');
const to_mem = comp(0x003000, 'to_mem');
const to_a   = comp(0x004000, 'to_a');
const to_pch = comp(0x005000, 'to_pch');

const to_out = comp(0x007000, 'to_out');  // has to be split-up in destination bits.

// Destination bits in output register

// New 8-10-2023. Set ALU to ADD (0x1d) otherwise can not select 1 condition.
// Due to the decoders, the OUT instruction will not write to a register, only to the '259
const to_sw_exx = comp(0x1d7000, 'to_sw_exx');
const l_to_sw_exx = comp(0x1d7000, 'l_to_sw_exx');  // select condition = 0
const h_to_sw_exx = comp(0x200000 + 0x1d7000, 'h_to_sw_exx'); // select condition = 1
const r0_to_sw_exx = comp(0xA00000 + 0x1d7000, 'r0_to_sw_exx'); // select condition r0 (for exx)
const c_to_sw_exx  = comp(0x400000 + 0x1d7000, 'c_to_sw_exx'); // cy variant 27-5-2024

// 4-2-2024 new bit destinations. These are mostly active low.

const l_to_sw_slot3    = comp(0x000000 + 0x1d7001, 'l_to_sw_slot3');  // 4-11-2024 slot 3
const h_to_sw_slot3    = comp(0x200000 + 0x1d7001, 'h_to_sw_slot3');
const l_to_sw_pc17     = comp(0x000000 + 0x1d7001, 'l_to_sw_pc17');  // 4-11-2024 pc17. Same bit as slot3
const h_to_sw_pc17     = comp(0x200000 + 0x1d7001, 'h_to_sw_pc17');
const tc_to_sw_pc17     = comp(0x600000 + 0x1d7001, 'tc_to_sw_pc17'); // 23-11-2024

const l_to_sw_wr_sound_n = comp(0x000000 + 0x1d7002, 'l_to_sw_wr_sound_n');  // sound and IRQ_ACK
const h_to_sw_wr_sound_n = comp(0x200000 + 0x1d7002, 'h_to_sw_wr_sound_n');
const c_to_sw_wr_sound_n = comp(0x400000 + 0x1d7002, 'c_to_sw_wr_sound_n'); // 27-11-2024
const l_to_sw_vdu_n      = comp(0x000000 + 0x1d7003, 'l_to_sw_vdu_n');  // video display, act low
const h_to_sw_vdu_n      = comp(0x200000 + 0x1d7003, 'h_to_sw_vdu_n');
const c_to_sw_vdu_n      = comp(0x400000 + 0x1d7003, 'c_to_sw_vdu_n'); // 27-11-2024

const l_to_sw_pc18      = comp(0x000000 + 0x1d7004, 'l_to_sw_pc18');  // 4-11-2024 pc18
const h_to_sw_pc18      = comp(0x200000 + 0x1d7004, 'h_to_sw_pc18');
const tc_to_sw_pc18     = comp(0x600000 + 0x1d7004, 'tc_to_sw_pc18');

const l_to_sw_pc19      = comp(0x000000 + 0x1d7007, 'l_to_sw_pc19');  // 18-11-2025 pc19
const h_to_sw_pc19      = comp(0x200000 + 0x1d7007, 'h_to_sw_pc19');
const tc_to_sw_pc19     = comp(0x600000 + 0x1d7007, 'tc_to_sw_pc19');

const l_to_sw_spi_cs1_n = comp(0x000000 + 0x1d7005, 'l_to_sw_spi_cs1_n');  // spi cs1
const h_to_sw_spi_cs1_n = comp(0x200000 + 0x1d7005, 'h_to_sw_spi_cs1_n');
const l_to_sw_spi_cs2_n = comp(0x000000 + 0x1d7006, 'l_to_sw_spi_cs2_n');  // spi cs2 RENAMED to kb_send 4-12-2024 cs2/ again
const h_to_sw_spi_cs2_n = comp(0x200000 + 0x1d7006, 'h_to_sw_spi_cs2_n');
//const c_to_sw_kb_send   = comp(0x400000 + 0x1d7006, 'c_to_sw_kb_send');  // kb_send  27-5-2024, 4-12-2024 removed  

const l_to_sw_gp_out1   = comp(0x000000 + 0x1d7007, 'l_to_sw_gp_out1');  // gp_out1
/* 13-11-2025
const h_to_sw_gp_out1   = comp(0x200000 + 0x1d7007, 'h_to_sw_gp_out1');
const dtc_to_sw_gp_out1 = comp(0xC00000 + 0x1d7007, 'dtc_to_sw_gp_out1'); // 16-4-2024 select condition dtc
*/
// 13-11-2025 have this I/O always 0 (testing)
const h_to_sw_gp_out1   = comp(0x000000 + 0x1d7007, 'l_to_sw_gp_out1');
const dtc_to_sw_gp_out1 = comp(0x000000 + 0x1d7007, 'l_to_sw_gp_out1'); // 16-4-2024 select condition dtc

// ALU  group 0 instructions

// 29-11-2023 toggled meaning of ctl_alu4 for group0
const ld_ir = comp(0x006000, 'ld_ir'); // load instruction register // 28-11-2023 IR is a dst now

const first_op = ld_ir; // 11-11-2023 for debugger

const ld   = comp(0x010000, 'ld');
const xor  = comp(0x060000, 'xor'); // 25-10-2023
const inp  = comp(0x020000, 'inp'); // 26-10-2023 input, only in combination with store to memory
const res  = comp(0x020000, 'res');
const res2 = comp(0x040000, 'res2'); // 20-3-2025  for copycnv

const shr = comp(0xa10010, 'shr'); // 7-9-2023 LD select bank1, 0xA00000 select D0 for cy (used for 6502)

const shrnew = comp(0xa10020, 'shrnew'); // 24-6-2025 LD with select bank2, 0xA00000 select D0 for cy, use with dph=0x01
                                         // "shrnew" for use with Z80 (and Symbos)

const lsr = comp(0xFFFFFF, 'lsr');  // 7-9-2023 only used as identifier, never as instruction
const ror = comp(0xFFFFFF, 'ror');  // 7-9-2023 only used as identifier, never as instruction

const zero = comp(0x000000, 'zero');  // 14-11-2023


// ALU  group 1 instructions

// 29-11-2023 toggled meaning of ctl_alu4. toggle bit 0x010000.
const ld_acc = comp(0x0c0000, 'ld_acc');  // 14-11-2023
const inc_acc = comp(0x2c0000, 'inc_acc');  // 14-11-2023
const dec_acc = comp(0x1d0000, 'dec_acc');  // 14-11-2023

const and = comp(0x080000, 'and');
const ldu = comp(0x0a0000, 'ldu');  // 6-7-2024 load through upper logic unit, for ZX Spectrum video (and SPI, 11-5-2025)
const inc = comp(0x2a0000, 'inc');
const inc_tc   = comp(0x6a0000, 'inc_tc');
const inc_dtc  = comp(0xca0000, 'inc_dtc');  // 16-10-2023
const inc_c    = comp(0x4a0000, 'inc_c');   // 12-5-2024 used for saving CY during video

const asl      = comp(0x0b0000, 'asl');
const shl_1    = comp(0x2b0000, 'shl_1'); // ??? was already 2b0000
const rol      = comp(0x4b0000, 'rol');
const rol_tc   = comp(0x6b0000, 'rol_tc');
const rol_dtc  = comp(0xcb0000, 'rol_dtc'); // 16-10-2023
const rol_miso = comp(0xab0000, 'rol_miso'); // 3-12-2024

const sub    = comp(0x3c0000, 'sub');    // subtract (add complement, ALU-cin=1)
const sub_0  = comp(0x1c0000, 'sub_0');  // subtract without setting ALU-cin
const compl  = comp(0x100000, 'compl'); // 19-3-2025  complement operand
const sbc    = comp(0x5c0000, 'sbc');
const sub_tc = comp(0x7c0000, 'sub_tc');
const sub_dtc= comp(0xdc0000, 'sub_dtc'); // 16-10-2023

const add    = comp(0x0d0000, 'add');
const add_1  = comp(0x2d0000, 'add_1'); //new 15-6 for TBL1
const adc    = comp(0x4d0000, 'adc');
const add_tc = comp(0x6d0000, 'add_tc');
const add_dtc= comp(0xcd0000, 'add_dtc'); // 16-10-2023
const or     = comp(0x0e0000, 'or');

const and_tst = comp(0x190000, 'and_tst'); // 30-12-2024 NEW. Does AND, and then ADD 0xFF, so it will set TC if result is NZ.
const or_tst  = comp(0x1f0000, 'or_tst');  // 27-04-2025 NEW. Does OR, and then ADD 0xFF, so it will set TC if result is NZ.
const xor_tst  = comp(0x170000, 'xor_tst');  // 20-5-2025 NEW. Does XOR, and then ADD 0xFF, so it will set TC if result is NZ.

const res2_tst = comp(0x150000, 'res2_tst'); // 11-6-2025 Does RES2, and then ADD 0xFF, so it will set TC if result is NZ.

const dec    = comp(0x1b0000, 'dec');    // 26-10-2023 new opcode for DEC
const dec_1  = comp(0x3b0000, 'dec_1');  // used for SEC (set carry)
const dec_tc = comp(0x7b0000, 'dec_tc');
const dec_dtc= comp(0xdb0000, 'dec_dtc'); // 16-10-2023

const last_op = dec_dtc; // 11-11-2023  for debugger
// 29-11-2023 end


// Source 1  ALU input1 selects between ACC_T and ACC_A:

const acc_t = comp(0x000000, 'acc_t');
const acc_a = comp(0x000080, 'acc_a');

// Source 2  ALU input2 can connect to many different sources:

// Source 2, memory access with zpage, full address, or program counter addressing:

// 23-11-2023  toggle ctl_m1

// 3-11-2024: const dir = comp(0x000300, 'dir'); 	// 0/dpl (to or from mem) (direct, 6800 term for zpage)
const dir = comp(0x000102, 'dir'); 	// 0/dpl (to or from mem) (direct, 6800 term for zpage) 3-11-2024 new
const pc_pp = comp(0x000008, 'pc_pp'); // 5-10-2023 was 008200. (pc) with auto increment
const pc_ind = comp(0x000000, 'pc_ind'); // 7-11-2023 (pc) without auto-increment
const inc_pc = comp(0x000008, 'inc_pc'); // 9-11-2023 increment pc. 
const ext = comp(0x000100, 'ext'); 	// dph/dpl (extended addressing, Z80 term for absolute)
const ext_msb = comp(0x000101, 'ext_msb'); // 29-10-2023 z80 aligned stack

// program counter indirect, in linear mode. ctl_bnk2 set. ctl_bnk0 can select other banks, not yet used (24-11-2024)
const pc_lin_pp =  comp(0x000048, 'pc_lin_pp');   // 24-11-2024  (pc) with auto increment. linear mode
const pc_lin_ind = comp(0x000040, 'pc_lin_ind'); // 24-11-2024 (pc) without auto-increment. linear mode

// Source 2, read from pch / pcl / dph / dpl

const bank_lit = comp_val[bank0]; // 30-10-2024 bank0
const bank_shr = comp_val[bank1]; // 21-11 bank1

// The PCL and DPL registers are now accessed through the 256-byte identity table (bank_lit)

// 30-10-2024  DPL, PCL use identity table in bank 2 (0x20)
const pcl = comp(0x000002 + 0x20, 'pcl');  // 13-11-2023 set 0x000002 ctl_reg1 (clr addr-high)
const dpl = comp(0x000102 + 0x20, 'dpl'); // 16-11 ctl_reg1=1 to clear addr-high

//const dpl_p1 =  comp(0x000301 + bank_lit,'dpl+1');// 29-10-2023 z80 aligned stack 15-11 not used 

// Source 2, registers:


// 17-4-2024 joined 6502-x with z80-ixl, similar with y/iy. Moved reg_tl/reg_th to swappable registers.

// 4-11-2024  new registers, 'bank3'. (no more real register banks in ISA2442)

//----- Registers in fixed banks -----

// free: swappable banks 1, 2 and 3. 24 registers. Bank0 can not be used. 
// Right-shifted literals are in bank1, taking 3 register positions there: 212, 214, 216 dont use them.

const reg_dbg       = comp(0x000220, 'reg_dbg');  // 11-1-2025  debugger. 0 -> off  bit7=1 -> on
const first_reg = reg_dbg; // 11-1-2025  for debugger, identification of first register

const reg_snd_ch    = comp(0x000221, 'reg_snd_ch'); // 20-5-2025 currently processed sound channel
const reg_ch_sel    = comp(0x000222, 'reg_ch_sel'); // 25-05-2025. psg channel that is modified by user
const reg_noise_lsb = comp(0x000223, 'reg_noise_lsb'); // 26-5-2025
const reg_noise_msb = comp(0x000224, 'reg_noise_msb'); // 26-5-2025

//const reg_psg_acc = comp(0x000225, 'reg_psg_acc'); // 1-10-2025 temporary test.

// snd pointer were at 221, 222.  Now put them elsewhere 226,227 0517C. No difference
const reg_snd_ptl   = comp(0x000226, 'reg_snd_ptl'); // 13-5-2025 sound output pointer
const reg_snd_pth   = comp(0x000227, 'reg_snd_pth');

const reg_os = comp(0x000230, 'reg_os');   // reg_os. Default 0. Set it to 0x40 to enable "out (c),reg" for bankswitching.
const reg_bank_pc = comp(0x000231, 'reg_bank_pc'); // 22-11-2024 keeps current selected pc18, pc17 (not yet used)
const reg_bank_dp = comp(0x000232, 'reg_bank_dp'); // 22-11-2024 keeps current selected dph/dpl bank value

// and 4 mouse registers here.

// registers for mouse RX device driver
const reg_mouse_bitbuf= comp(0x000233, 'reg_mouse_bitbuf'); // 27-11-2024
const save_acc        = comp(0x000233, 'save_acc'); // 28-2-2025
const reg_mouse_state = comp(0x000234, 'reg_mouse_state'); 
const reg_mouse_ptin  = comp(0x000235, 'reg_mouse_ptin'); 
const reg_mouse_ptout = comp(0x000236, 'reg_mouse_ptout'); 
const reg_sound       = comp(0x000237, 'reg_sound');  // 5-12-2024 contains next sound sample



// 24-11 signal swap
// 23-11-2023  remove 0x008000 from register codes and toggle ctl_m1 0x000200
// 6-9-2023 new,  add 0x20 to every register code (reg4 bit), forcing registers in bank 4-7
// reg 0-7  bank 4 and 5
const reg_v = comp(0x000240, 'reg_v');   // flag_v  6502/Z80
const reg_s   = comp(0x000241, 'reg_s');   // 6502 stackpt
const reg_spl = comp(0x000241, 'reg_spl');  // z80 spl, z80 and 6502 stackpt same addr !
const reg_x   = comp(0x000242, 'reg_x');   // 6502
const reg_ixl = comp(0x000242, 'reg_ixl');  // 17-4-2024
const reg_y   = comp(0x000243, 'reg_y');   // 6502
const reg_iyl = comp(0x000243, 'reg_iyl');  // 17-4-2024
const reg_z   = comp(0x000244, 'reg_z');   // 6502/Z80 flag z
const reg_f_alt_cy = comp(0x000245, 'reg_f_alt_cy');  // z80 alt cy  31-10-2023
const reg_128 = comp(0x000246, 'reg_128');  // 7-9-2023 contains fixed 0x80 value
const reg_sph = comp(0x000247, 'reg_sph');  // z80 sp

// 25-7-2023 more registers, with ctl_reg3 (0x000400) = 1 (that means another RAM bank)
// reg 8-15 bank 5
const reg_0F = comp(0x000250, 'reg_0F'); // 23-6-2024  contains fixed 0x0F value
const reg_snd_pt = comp(0x000251, 'reg_snd_pt'); // 15-6-2024
const reg_ixh = comp(0x000252, 'reg_ixh');
const reg_iyh = comp(0x000253, 'reg_iyh');
const reg_i   = comp(0x000254, 'reg_i'); // 2-10-2024 register i
const reg_irq = comp(0x000255, 'reg_irq'); // 2-10-2024 register irq
const reg_a_alt = comp(0x000256, 'reg_a_alt');
const reg_f_alt = comp(0x000257, 'reg_f_alt');


const reg_flags = reg_v; // z80 flags

// 4-2-2024 new registers in bank 6 en 7

const reg_silence_cnt = comp(0x000260, 'reg_silence_cnt');   // 18-9-2025

const reg_kbcount = comp(0x000261, 'reg_kbcount'); // 4-2 // 26-2-2025 no longer used
const reg_isa = comp(0x000262, 'reg_isa'); // 4-3-2024 hold the current processor type 6502/Z80/Blitter

// registers for keyboard RX device driver
const reg_kb_bitbuf = comp(0x000263, 'reg_kb_bitbuf'); // 8-4-2024
const save_opcode   = comp(0x000263, 'save_opcode'); // 28-2-2025
const reg_kb_state = comp(0x000264, 'reg_kb_state'); // 8-4-2024 // 23-9-2025 value < 128 indicates shutdown state
const reg_kb_ptin = comp(0x000265, 'reg_kb_ptin'); // 8-4-2024
const reg_kb_ptout = comp(0x000266, 'reg_kb_ptout'); // 8-4-2024

// registers for debug output TX chars
const reg_tx_bitbuf = comp(0x000267, 'reg_tx_bitbuf');   // 9-4-2024
const save_page     = comp(0x000267, 'save_page'); // 28-2-2025
const reg_tx_ptin = comp(0x000271, 'reg_tx_ptin'); // 9-4-2024  Bank 7
const reg_tx_ptout = comp(0x000272, 'reg_tx_ptout'); // 9-4-2024
const reg_tx_state = comp(0x000273, 'reg_tx_state'); // 16-4-2024

// registers for sound device driver
const reg_sound_state = comp(0x000270, 'reg_sound_state'); // 10-4-2024

// registers for video device driver
const reg_vga_ptl = comp(0x000274, 'reg_vga_ptl'); // 29-4-2024
const reg_vga_pth = comp(0x000275, 'reg_vga_pth'); // 29-4-2024
const reg_vga_base = comp(0x000276, 'reg_vga_base'); // 29-4-2024 <-- candidate for moving to slower register.

const reg_speaker = comp(0x000277, 'reg_speaker'); // 15-6-2024 Speaker output stored here (ZX Spectrum)


//----- registers in swappable banks -----

// free: swappable banks 0, 1, 2 and 3. 32 registers.

// The following 8 registers r16 - r23 are swappable, they swap with r24 - r31
// bank 4 and 5
const reg_b = comp(0x000248, 'reg_b'); // Z80, swappable register set r16 - r23
const reg_c = comp(0x000249, 'reg_c');
const reg_d = comp(0x00024a, 'reg_d');
const reg_e = comp(0x00024b, 'reg_e');
const reg_h = comp(0x00024c, 'reg_h');
const reg_l = comp(0x00024d, 'reg_l');
const reg_sel= comp(0x00024e, 'reg_sel');
const reg_exx= comp(0x00024f, 'reg_exx'); // 27-3-2025 must be in reg bank 1 (high).
const reg_th = comp(0x000258, 'reg_th');   // 17-4-2024 here. temporary register-high
const reg_tl = comp(0x000259, 'reg_tl');   // 17-4-2024.  temporary register-low
const reg_kb_tmp  = comp(0x00025A, 'reg_kb_tmp');  // 15-5-2024 used in KB read and TX, 13-5-2025 in wr_sound
const reg_vga_acc = comp(0x00025B, 'reg_vga_acc');   // 12-5-2024 to save ACC during video interrupt. And used in LDIR.
const reg_vga_flags  = comp(0x00025C, 'reg_vga_flags');   // 12-5-2024 to save flags N,C during video interrupt
const reg_vga_msb  = comp(0x00025D, 'reg_vga_msb');  // 17-5-2024  same as reg_psg_tmp
const reg_psg_tmp  = comp(0x00025D, 'reg_psg_tmp');  // 12-6-2024  same as reg_vga_msb !
const reg_vga_lsb  = comp(0x00025E, 'reg_vga_lsb');  // 17-5-2024  also used in sound
// free: 025F

// free: swappable banks 6 and 7. 16 registers.


// Normal registers are at address 00, 01, 08, 09, 0x20, 0x21, 0x28 and 0x29
// For the exchangeable registers, add 0x02 for first register set, and 0x06 for second register set
// Available positions are where 0x04 is added to the normal registers.
// reg_user_zx_kb = 4;   MSB of keyboard routine for ZX Spectrum, bank4, address 0004
// reg_user_mute = 5;   MSB of keyboard routine for ZX Spectrum, bank4, address 0005. Has 00 when muted, FF when sound on

// Registers in swappable banks, used as inputs for the BLITTER

const dst_x_l = comp(0x000208, 'dst_x_l'); // destination (screen)
const dst_x_h = comp(0x000209, 'dst_x_h');
const dst_y_l = comp(0x00020a, 'dst_y_l');
const dst_y_h = comp(0x00020b, 'dst_y_h');
const src_x_l = comp(0x00020c, 'src_x_l'); // source
const src_x_h = comp(0x00020d, 'src_x_h');
const src_y_l = comp(0x00020e, 'src_y_l'); 
const src_y_h = comp(0x00020f, 'src_y_h');
const src_a_l = comp(0x000218, 'src_a_l'); // source addr
const src_a_h = comp(0x000219, 'src_a_h');
const src_a_u = comp(0x00021a, 'src_a_u'); // upper byte
const src_l_l = comp(0x00021b, 'src_l_l'); // src line length
const src_l_h = comp(0x00021c, 'src_l_h'); 
const size_x_l = comp(0x00021d, 'size_x_l'); // size
const size_x_h = comp(0x00021e, 'size_x_h');
const size_y_l = comp(0x00021f, 'size_y_l');
const size_y_h = comp(0x000228, 'size_y_h');
const fill_1 = comp(0x000229, 'fill_1'); // fill
const fill_2 = comp(0x00022a, 'fill_2');

// 22-11-2024 temporary registers for Blitter. Can also be used for other things when blitter not active

const t_label1 = comp(0x00022b, 't_label1'); 
const t_label2 = comp(0x00022c, 't_label2');
const t_label3 = comp(0x00022d, 't_label3');
const t_label4 = comp(0x00022e, 't_label4');
const t_label5 = comp(0x00022f, 't_label5'); 
const t_pc_lsb = comp(0x000238, 't_pc_lsb');
const t_pc_msb = comp(0x000239, 't_pc_msb'); 
const t_txt_lsb= comp(0x00023a, 't_txt_lsb'); // 31-12-2024
const t_dp_lsb = comp(0x00023b, 't_dp_lsb'); 
const t_dp_msb = comp(0x00023c, 't_dp_msb');
const t_dp_upb = comp(0x00023d, 't_dp_upb'); 
const t_bytecount = comp(0x00023e, 't_bytecount'); 
const t_bytecount_msb = comp(0x00023f, 't_bytecount_msb'); 

// continue in bank 6
const t_count_msb = comp(0x000268, 't_count_msb'); 
const t_temp_reg_isa = comp(0x000269, 't_temp_reg_isa');
const t_save_dpl = comp(0x00026a, 't_save_dpl');
const t_save_dph = comp(0x00026b, 't_save_dph');
const t_save_t   = comp(0x00026c, 't_save_t');
const t_temp_pcl = comp(0x00026d, 't_temp_pcl');
const t_temp_pch = comp(0x00026e, 't_temp_pch');

const t_fill_1_sh4 = comp(0x00026f, 't_fill_1_sh4'); // fill shifted 4 bits
const t_fill_2_sh4 = comp(0x000278, 't_fill_2_sh4'); // 

const t_linecount = comp(0x000279, 't_linecount'); // 3-1-2025

const last_real_reg = t_linecount; // 28-2-2025

// end blitter registers

// 71 - 7f free


//*********  end of microcode bit patterns  *********/


// 6-2-2024 create values 0-63 (doubled) to be used for downloading.
// These values are stored in RAM and overlap with register values.
// It uses banks 3, 5, 6, 7.  Not use bank 4 because that has reg128 that we will need.

// The following loop creates val0 - val63 as 'registers' (even values only)
//  val0 -> 0
//  val1 -> 2
//  val2 -> 4
//  val3 -> 6
//  ...
//  val63 -> 126
var val0 = compnr + 1;  // this is value 0. 
var ii = 0;
while (ii <= 63) {
	var bnk = (ii & 0x30) + 0x40; // use 4 banks, 0x40, 0x50, 0x60, 0x70 
	if (bnk == 0x40) bnk = 0x30; // use 0x30 instead of 0x40
	var lower = ii & 0x0F; // lower four bits used as-is, for Hi, r2, r1, r0
	comp(0x200 + bnk + lower, "val" + (2 * ii));
	ii++;
}

var hex_0 = compnr + 1;  // make a list of 256 values 00-FF, used as comment
ii = 0;
while (ii <= 255) {
	comp(0, "hex_" + hexstring2(ii)); // it's value is 0 (nop)
	ii++;
}


// Now comes the function that fills the registers val0-val63 with values 0-126.
// This action is performed after a reset, before the application program starts.
// This corrupts all mem-based registers except those in bank 4.

function init_values(page, name) {
	var section = 0; // 8 sections that each initialize 8 values
	while (section <= 7) {
		opc = 0x16 + section; // opcode 0x16 in reset page
		opcode_page(page, opc, name, nop, nop);
		var int = 0;
		// value should already be in A ( zero for first one ). DPL must already be 2.
		while (int <= 7) {
			ins6(nop, to_mem, ld, acc_a, val0 + ((section << 3) + int), nop); // write A to the numbered value register
			ins6(nop, to_a, add, acc_a, dpl, upd_f); // A <- A + 2 (dpl=2)
			int++;
		}
		print_cycles();
		section++;
	}
	opc = 0x16 + section; // next opcode after initialization of values
	opcode_page(page, opc, name, nop, nop);

	ins6(nop, to_t, ld, acc_a, reg_128, nop); // init T to 128

	// 5-3-2024 new:   Put the application program at address E000
	instr_val(to_pch, 0x00); // LSB of destination addr (address E000)
	instr_val(to_pch, 0xE0); // MSB of destination addr (should be 0)

	ins6(nop, to_t, ld_ir, acc_t, lit0, page_download); // jump to download DATA

	ins6(delay_m, nop, nop, nop, nop, nop);

	print_cycles();

	/*
	// 5-3-2024 remove the next part, going for a simpler system
	// This part needs the target address in H L !  
	// the code with the program should do following:
	//  - a <- data
	//  - save a in reg_b
	//  - a <- data 
	//  - dpl <- data
	//  - pch <- data
	//  - pch <- data
	//  - T <- data
	//  - return, to 0x09 in page_reset
    
  
	// next instruction might get a name !!
	opcode_page(page,0x09,name,nop,nop);  // the instruction after the data. opcode 0x09 and 0x0A
	// save A, pch, pcl to have room for transfer register and pointer
	ins6(nop,to_mem,ld,acc_a,reg_c,nop); // reg_C <- A 
	ins6(nop,to_a,ld,acc_a,pcl,nop);     // A <- pcl 
	ins6(nop,to_mem,ld,acc_a,reg_d,nop); // reg_D <- A  
	ins6(nop,to_pch,ld,acc_a,lit0,nop);  // pcl <- pch
	ins6(nop,to_a,ld,acc_a,pcl,nop);     // A <- pcl 
	ins6(nop,to_mem,ld,acc_a,reg_e,nop); // reg_E <- A     
	// load the pointer from HL into PC
	ins6(nop,to_a,ld,acc_a,reg_l,nop);     // A <- L 
	ins6(nop,to_pch,xor,acc_a,lit0,nop);   // pch <- A
	ins6(nop,to_a,ld,acc_a,reg_h,nop);     // A <- H 
	ins6(nop,to_pch,xor,acc_a,lit0,nop);   // pch <- A
	// start moving the data
	ins6(nop,to_a,ld,acc_a,reg_b,nop);     // A <- B
	ins6(nop,to_mem,ld,acc_a,pc_pp,nop);   // (pc++) <- A
	ins6(nop,to_a,ld,acc_a,reg_c,nop);     // A <- C
	ins6(nop,to_mem,ld,acc_a,pc_pp,nop);   // (pc++) <- A  
	ins6(nop,to_a,ld,acc_a,dpl,nop);       // A <- dpl
	ins6(nop,to_mem,ld,acc_a,pc_pp,nop);   // (pc++) <- A  
  
	ins6(nop,to_a,ld,acc_a,reg_d,nop);     // A <- D
	ins6(nop,to_mem,ld,acc_a,pc_pp,nop);   // (pc++) <- A
	ins6(nop,to_a,ld,acc_a,reg_e,nop);     // A <- E
	ins6(nop,to_mem,ld,acc_a,pc_pp,nop);   // (pc++) <- A  
	ins6(nop,to_mem,ld,acc_t,pc_pp,nop);   // (pc++) <- T
	// done moving the data. Save PC to HL
	ins6(nop,to_a,ld,acc_a,pcl,nop);     // A <- pcl 
	ins6(nop,to_mem,ld,acc_a,reg_l,nop); // reg_L <- A  
	ins6(nop,to_pch,ld,acc_a,lit0,nop);  // pcl <- pch
	ins6(nop,to_a,ld,acc_a,pcl,nop);     // A <- pcl 
	ins6(nop,to_mem,ld,acc_a,reg_h,nop); // reg_H <- A    
	//
	ins6(nop,to_a,inc,acc_a,reg_x,nop);     // A <- reg_x + 1 
  
	// have to test for the last reg_x value, then quit. TO DO
	// Quit if TC is active  TO DO. 
	// It will simply jump to the application: PC <- addr, IR <- (pc++), page_6502_or_Z80
  
	ins6(nop,to_mem,ld,acc_a,reg_x,nop);    // reg_x <- A   
	// 
	ins6(nop, to_t, ld_ir, acc_t, reg_x, page_download); // jump to 'instruction'
	ins6(nop,to_t,ld,acc_a,reg_128,nop); // init T to 128
	*/

	// now comes the stored data, that will be downloaded to RAM directly after reset

	var this_page = page_download;
	var download_addr = 0xE000; // start the program at E000
	var section_last = 16;
	const page_end = 0x99;
	var section = 0;
	// two pages and a few other locations used for download, E000 - EFFF
	while (this_page != page_end) {
		while (section < section_last) { // each section is 16 consecutive opcodes. There are 8 download-bytes max in
			// an opcode, so the max is 128, but it will be a few less because a jump to
			// the next section must be added
			opcode_page(this_page, section << 4, 'DATA', nop, nop);
			commentline("Next address " + hexstring(download_addr));
			var byte_count = 0;
			var byte = 0;
			while (byte_count < 126) {
				byte = memory[download_addr++];

				if (microcode[micro_pc] != undefined) {					
					commentline("*** ERR page: " + this_page + " section: 0x" + hexstring(section)
						+ " Data position already defined, it is " + hexstring(microcode[micro_pc]));
					alert("page: " + this_page + " section: 0x" + hexstring(section) + " Opcode already defined");
				}

				instr_val(to_a, byte);  // generate an instruction to put the byte in accumulator
				// note that the T register must be 0x80
				ins6(nop, to_mem, ld, acc_a, pc_pp, nop); // put the byte at (PC) and increment PC
				byte_count++;

				if (byte_count == 2) {   // 21-9-2025 was count=4
					commentline("-- (Several output lines not printed) --");
					listing_on = 0;
				}
				if (byte_count == 124) {  // 21-9-2025 was count=123
					listing_on = 1;
				}
			}
			section++;  // select next section
			commentline("-- Jump to next section");
			// now generate a jmp to the next section, or to the launch
			if (short_download == 1)   // 14-4-2024 if Short_download, only the range E000 - E07D is downloaded
			{
				instr_val(to_dpl, 0x09); // opcode number of launch
				ins6(nop, to_t, ld_ir, acc_t, dpl, page_reset); // jp to launch
				this_page = page_end;
				section_last = 1;
				section = 1; // stop the loop
			}
			else
				if (section != section_last) {
					instr_val(to_dpl, section << 4); // opcode number is 16 times section number
					ins6(nop, to_t, ld_ir, acc_t, dpl, this_page); // jp to next section
				}
				else
					/* 21-9-2025
					if (this_page == page_download)	// still on first page ? goto next
					{
						ins6(nop, to_t, ld_ir, acc_t, lit0, page_download2); // jp to next section
						this_page = page_download2;
						section = 0;
					}
					else
						if (this_page == page_download2)	// still on second page ? goto next
						{  // the last part is on the reset page.
							instr_val(to_dpl, 0xc0); // opcode number of data in reset page
							ins6(nop, to_t, ld_ir, acc_t, dpl, page_reset); // jp to next section
							this_page = page_reset;
							section_last = 0x0D; // only section 0x0C  (but a few bytes more than needed)
							section = 0x0C;  // 
						}
						else	 // must be page_reset 
						{
							instr_val(to_dpl, 0x09); // opcode number of launch
							ins6(nop, to_t, ld_ir, acc_t, dpl, page_reset); // jp to launch
							this_page = page_end;
						}
					*/  // end 21-9-2025
					// 21-9-2025
					if (this_page == page_download)	// still on first page ? goto next
					{	ins6(nop, to_t, ld_ir, acc_t, lit0, page_download2); // jp to next section
						this_page = page_download2;
						section = 0;
					}
					else
					    // from download2 to downloads, start at C0 in page-sound (22) 22-9-2025 not use page_sound. download3 is page 24, full page.
						if (this_page == page_download2)	// still on second page ? goto next
						{ 	ins6(nop, to_t, ld_ir, acc_t, lit0, page_download3); // jp to next section  22-9-2025 use full page
							this_page = page_download3;  // 21-9-2025 changed to download3						
							section = 0
						}					
					else
						if (this_page == page_download3)	// still on second page ? goto next
						{ 	instr_val(to_dpl, 0x09); // opcode number of launch
							ins6(nop, to_t, ld_ir, acc_t, dpl, page_reset); // jp to launch
							this_page = page_end;
						}
						else	 // must be page_reset (unused)
						{	instr_val(to_dpl, 0x09); // opcode number of launch
							ins6(nop, to_t, ld_ir, acc_t, dpl, page_reset); // jp to launch
							this_page = page_end;
						}					
			ins6(delay_m, nop, nop, nop, nop, nop);
			commentline("Next address " + hexstring(download_addr));
			print_cycles();
		}
	}

	opcode_page(page, 0x09, 'LAUNCH', nop, nop);  // the instruction after the data. opcode 0x09, (continuing in 0x0A !! ) 

	// 7-6-2024  fixed startaddress of loader, E000
	instr_val(to_pch, 0x00); // LSB, set program counter to 0xE000   for loader and Apple 1.
	instr_val(to_pch, 0xE0); // MSB

	// Moving literals (like ISA_6502) to a memory-based register can be tricky. After reset, many registers were
	// filled with literal values. So, a write to a register can overwrite a literal value. Use
	// with care !

    if (processortype == processor_z80)
	   instr_val(to_a, ISA_Z80);  // 21-4-2024
	else instr_val(to_a, ISA_6502);
	ins6(nop, to_mem, ld, acc_a, reg_isa, nop); // set processor type (in 'reg_isa') to selected processor

	instr_val(to_a, 0xC0); // 25-11-2024 default value for OS bankswitching system
	ins6(nop, to_mem, ld, acc_a, reg_i, nop); // 25-11-2024  OS bankswitching, set reg_i = 0xC0


	// 6-3-2024  Initialize the state of the device drivers

	instr_val(to_a, SOUND_STATE_IDLE);  // 11-4-2024  set A to SOUND_STATE_IDLE (needs T = 128 !)
	ins6(nop, to_mem, ld, acc_a, reg_sound_state, nop); // 10-4-2024 initialize state of the sound driver

	ins6(nop, to_a, inc, acc_t, reg_128, nop); // set A to 0x81  (first Keyboard state)
	ins6(nop, to_mem, ld, acc_a, reg_kb_state, nop); // 10-4-2024 initialize state of the keyboard driver

	make_literal(to_a, MOUSE_STATE_WAIT);
	ins6(nop, to_mem, ld, acc_a, reg_mouse_state, nop); // 27-11-2024 initialize state of the mouse driver

	ins6(nop, to_a, ld, acc_t, lit0, nop); // set A to 0

	// 3-11-2024  no muting, bank4 can be used no longer
	ins6(nop, to_dpl, inc, acc_t, lit4, nop); // value 5,  reg_user_mute, to dpl  MUTE 21-6-2024
	// 3-11: ins6(nop, to_mem, ld, acc_a, dir, bank4); // set MUTE to zero, reg_user_mute in bank4, sound is muted	
	//ins6(nop, to_mem, ld, acc_a, dir, bank4); // 26-11-2024 yes, we can still use this user registers. Even in bank4.
	// 27-2-2025 Above line, writing to bank4, is incorrect. Overwrites lit33 with 0. Cause problem in blitter.

	ins6(nop, to_mem, ld, acc_a, reg_kb_ptin, nop);  // 10-4-2024 initialize in- and out pointers for KB and TX devices
	ins6(nop, to_mem, ld, acc_a, reg_kb_ptout, nop);
	ins6(nop, to_mem, ld, acc_a, reg_tx_ptin, nop);
	ins6(nop, to_mem, ld, acc_a, reg_tx_ptout, nop);
	ins6(nop, to_mem, ld, acc_a, reg_mouse_ptin, nop);  // 27-11-2024
	ins6(nop, to_mem, ld, acc_a, reg_mouse_ptout, nop);	// 27-11-2024
	ins6(nop, to_mem, ld, acc_a, reg_os,nop);  // 21-12-2024 set reg_os to 0x00	
	ins6(nop, to_mem, ld, acc_a, reg_dbg,nop);  // 11-1-2025 set reg_dbg to 0x00	
	ins6(nop, to_mem, ld, acc_a, reg_ch_sel, nop);	// 15-8-2025 reset bit7, otherwise there is no video

	ins6(nop, to_a, dec, acc_t, lit0, nop);	     // put FF in acc
	ins6(nop, to_mem, ld, acc_a, reg_tx_state, nop);  // tx state init to FF

	// 2-10-2024 init reg_irq. Initialize reg_irq in reset. reg_irq should be F7. Use the fact that reg_tx_state = FF.
  	ins6(nop,to_t,ld,acc_t,lit8, nop); // T <- 8
  	ins6(nop,to_t,res,acc_t,reg_tx_state, nop);    // T <- T res FF (reset bit T in reg_irq). Frame interrupts disabled.
  	ins6(nop,to_mem,ld,acc_t,reg_irq, nop); 

	// 30-12-2024  Get bank register value  with appl=1, bank=3. (bank register was initialized in reset)
	ins6(nop, to_a, dec, acc_t, lit0, nop);	 // A <- FF
	ins6(nop, to_a, sub, acc_a, lit4, nop);  // A <- A -4; A = 1111 1011
	ins6(nop, to_a, res2, acc_a, lit8, nop); // new 17-11-2025, reset bit 3 (a19=0)
    ins6(nop, to_mem, ld, acc_a, reg_bank_dp, nop);	 // store a copy of the bankswitch value	

	// Initialize the video frame counter and frame start address

	ins6(nop, to_t, dec, acc_t, lit0, nop);  // 0xFF to T
	ins6(nop, to_mem, ld, acc_t, reg_vga_ptl, nop);	 // reg_vga_ptl <- T

	ins6(nop, to_t, inc, acc_t, lit1, nop);  // T  <- 2  
	ins6(nop, to_t, add, acc_t, lit4, nop);  // T  <- T + 4  for addr 06FF  1-7-2025	
	ins6(nop, to_mem, ld, acc_t, reg_vga_pth, nop);	 // reg_vga_pth <- T
	// vga_pth/vga_ptl is now initialized to 0x06FF
    // the next interrupt will first increment this so first addr is 0x0700		

    ins6(nop, to_t, dec, acc_t, lit8, nop);   // T <- 7   1-7-2025
	ins6(nop, to_mem, ld, acc_t, reg_vga_base, nop);  // reg_vga_base  <- 0x07	 1-7-2025

    // place a video instruction V_REPEAT at the first address in the frame
	ins6(nop, to_dph, ld, acc_t, reg_vga_base, nop);  // set address to 0x0300 (now 0x0700 1-7-2025)
	ins6(nop, to_dpl, ld, acc_t, lit0, nop);	
	ins6(nop, to_t, ld, acc_t, lit4, nop); 
    ins6(nop, to_t, add, acc_t, lit40, nop); // V_RPT instruction, 0x2C ( dec 40 + 4 )

    ins6(nop, to_mem, ld, acc_t, ext, bank1);  // mem <- V_REPEAT  in bank 1 !

	// 4-11-2024 initialize OS register, set to 0x40 if OS might be present. controls out (c),reg
    // 21-12-2024 default is now 0.
    //ins6(nop, to_t, asl, acc_t, lit32, nop);
    //ins6(nop, to_mem, ld, acc_t, reg_os,nop);  // set reg_os to 0x40

	// initialize Z80 EXX switch function

	// 8-10-2023 new init of EXX switch function.
	ins6(nop, h_to_sw_exx, ld, acc_t, lit0, nop);	// set SW_EXX to 1
	ins6(nop, to_t, inc, acc_t, lit0, nop);		    // set T to 1  
	ins6(nop, to_mem, ld, acc_t, reg_sel, nop);		// write T to reg_sel of reg_bank 1	

	ins6(nop, l_to_sw_exx, ld, acc_t, lit0, nop);	// set SW_EXX to 0
	ins6(nop, to_t, zero, acc_t, lit0, nop);		// set T to 0
	ins6(nop, to_mem, ld, acc_t, reg_sel, nop);		// write T to reg_sel of reg_bank 0

	// Initialize reg_0F (used for RRD instruction)
	ins6(nop, to_t, dec, acc_t, lit8, nop);  // T  <- 7
	ins6(nop, to_t, add, acc_t, lit8, nop);  // T  <-  T + 8		
	ins6(nop, to_mem, ld, acc_t, reg_0F, nop);		// write T to reg_0F	 

	ins6(nop, to_mem, ld, acc_t, reg_sound, nop);	// 8-12-2024  sound reg default 0F

	// 13-5-2025. sound reg pointer MSB start at 1000. First 1K samples will be wrong, because it should start at 1400
	// 14-5-2025 but after reset, set it to #80 to indicate mute.
	ins6(nop, to_t, ld, acc_t, reg_128, nop);	 // value 0x80
	ins6(nop, to_mem, ld, acc_t, reg_snd_pth, nop);	// 13-5-2025  .
	
	// 8-12-2024 end

	// 2-10-2024 next instr, clr F.
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to first instruction of selected processor
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024  no irq_to_f

	print_cycles();
}



function instr_val(dst, num)
// generate instruction needed to get the number into the destination.
// instructions can be: ld, inc, add, add_1
// When using this, T must contain 128
{
	var instr_num = val0 + ((num & 0x7E) >> 1); // middle 6 bits give val0 - val63

	if ((num & 0x81) == 0x00) opc = ld;        // value 0xxx xxx0
	else if ((num & 0x81) == 0x01) opc = inc;  // value 0xxx xxx1
	else if ((num & 0x81) == 0x80) opc = add;  // value 1xxx xxx0  Add T (T=128)
	else if ((num & 0x81) == 0x81) opc = add_1;// value 1xxx xxx1  Add T with Cin=1	
	else alert("instr_val error");

	ins6(nop, dst, opc, acc_t, instr_num, hex_0 + num);
}

// Source 2, get a literal value (immediate value)

// Basic literal values

// Bank1 has values shifted right: 0x000004
// Bank2 has straight values: 0x000400

const lit_bit0 = 0x000201;     // ctl_reg0  0x01
const lit_bit1 = 0x000208;     // ctl_hi    0x02 Do not use this for literals
const lit_bit3 = 0x000202;     // ctl_reg2  0x08
const lit_bit5 = 0x000204;     // ctl_reg1  0x20


const lit0 = comp(0x000200 | bank_lit, 'lit0'); // 23-11-2023 toggle ctl_m1
const lit8 = comp(lit_bit3 | bank_lit, 'lit8');
const lit32 = comp(lit_bit5 | bank_lit, 'lit32');

const lit1 = comp(lit_bit0 | bank_lit, 'lit1');
const lit9   =  comp(           lit_bit3 | lit_bit0 | bank_lit,'lit9');  // 11-7-2024 used now in out_isa
const lit33  =  comp(lit_bit5 |            lit_bit0 | bank_lit,'lit33'); // 2-10-2024
const lit40  =  comp(lit_bit5 | lit_bit3 |            bank_lit,'lit40'); // 12-5-2024 in video
const lit41  =  comp(lit_bit5 | lit_bit3 | lit_bit0 | bank_lit,'lit41'); // 2-10-2024

const lit4 = comp(lit_bit3 | bank_shr, 'lit4');
const lit16 = comp(lit_bit5 | bank_shr, 'lit16');
const lit20 = comp(lit_bit5 | lit_bit3 | bank_shr, 'lit20');

const last_reg = lit20; // 21-11-2023  last of registers and literals


// Update flags:

// 6-9- new, z flag is meaningless (removed)  now:
// 24-11
const upd_n = comp(0x000400, 'upd_n');
const upd_z = comp(0x000000, 'upd_z');
const upd_nz = comp(0x000400, 'upd_nz');
const upd_c = comp(0x008000, 'upd_c');
const cpl_c = comp(0x408000, 'cpl_c'); // note 0x400000 selects C  22-7
const clr_c = comp(0x208000, 'clr_c'); // 12-11-2023
const set_c = comp(0x008000, 'set_c'); // 12-11-2023

const upd_nc = comp(0x008400, 'upd_nc');
const upd_zc = comp(0x008000, 'upd_zc');
const upd_nzc = comp(0x008400, 'upd_nzc');

const spi1_clkh = comp(0x008C00, 'spi1_clkh'); // 9-4-2025  same again as for spi2
const spi2_clkh = comp(0x008C00, 'spi2_clkh'); // 27-3-2025A  use all 3 signals upd_n, upd_c, wr_f

// values that do not directly represent control signals:

// Accumulators A and T

const reg_a = comp(0xFFFF70, 'reg_a');
const reg_t = comp(0xFFFF70, 'reg_t');

// 6502 addressing modes

const imm = comp(0xFFFF70, 'imm');
const zp = comp(0xFFFF70, 'zp');
const zpx = comp(0xFFFF70, 'zpx');
const zpy = comp(0xFFFF70, 'zpy');
const abs = comp(0xFFFF70, 'abs');
const absx = comp(0xFFFF70, 'absx');
const absy = comp(0xFFFF70, 'absy');
const idx = comp(0xFFFF70, 'idx_indexed_indirect');
const idy = comp(0xFFFF70, 'idy_indirect_indexed');
const ind = comp(0xFFFF70, 'indirect'); // for jumps

const error = comp(0xFFFF70, 'error');
const empty = comp(0xFFFF70, "");
const flag_v = comp(0xFFFF70, "flag_v");

const bitnr0 = comp(0, "0");
const bitnr1 = comp(1, "1");
const bitnr2 = comp(2, "2");
const bitnr3 = comp(3, "3");
const bitnr4 = comp(4, "4");
const bitnr5 = comp(5, "5");
const bitnr6 = comp(6, "6");
const bitnr7 = comp(7, "7");

// Z80 addressing modes

const ind_bc = comp(0xFFFF70, '(bc)');
const ind_de = comp(0xFFFF70, '(de)');
const ind_hl = comp(0xFFFF70, '(hl)');
const ind_sp = comp(0xFFFF70, '(sp)');
const ind_ix_d = comp(0xFFFF70, '(ix+d)');
const ind_iy_d = comp(0xFFFF70, '(iy+d)');

const ind_c = comp(0xFFFF70, '(c)'); // 7-6-2024 only for in a,(c) and out (c),a

// Z80 register pairs

const pair_bc = comp(0xFFFF70, 'bc');
const pair_de = comp(0xFFFF70, 'de');
const pair_hl = comp(0xFFFF70, 'hl');
const pair_sp = comp(0xFFFF70, 'sp');
const pair_ix = comp(0xFFFF70, 'ix');
const pair_iy = comp(0xFFFF70, 'iy');
const pair_af = comp(0xFFFF70, 'af');
const pair_pc = comp(0xFFFF70, 'pc');
const pair_th_tl = comp(0xFFFF70, 'th-tl'); // 1-11-2025 debugger stores pc in th-tl

// Z80 shift instructions

const rla = comp(0xFFFF70, 'rla');
const rlca = comp(0xFFFF70, 'rlca');
const rra = comp(0xFFFF70, 'rra');
const rrca = comp(0xFFFF70, 'rrca');

const rl = comp(0xFFFF70, 'rl');
const rlc = comp(0xFFFF70, 'rlc');
const rr = comp(0xFFFF70, 'rr');
const rrc = comp(0xFFFF70, 'rrc');

const sla = comp(0xFFFF70, 'sla');
const sra = comp(0xFFFF70, 'sra');
const srl = comp(0xFFFF70, 'srl');

// Z80 special instructions

const cp = comp(0xFFFF70, 'cp');  // z80 compare
const ex = comp(0xFFFF70, 'ex');  // z80 exchange register pair
const push = comp(0xFFFF70, 'push');
const pop = comp(0xFFFF70, 'pop');
const z80_bit = comp(0xFFFF70, 'z80_bit');
const z80_set = comp(0xFFFF70, 'z80_set');
const z80_res = comp(0xFFFF70, 'z80_res');


// define 'macro's'   

// 'next' will load the next instruction into the instruction register
// 'delay' is to be used after the 'next' instruction if there is no useful instruction that can be put there
// 'delay' will also load the IRQ condition into the F flag
// 'null' is the same as delay but it does not change the F flag
// 'interrupt' will do a jump to the interrupt microinstruction. 


const next_m = comp(0, 'next');
const interrupt_m = comp(0, 'interrupt');

// The next_m will be re-defined for 6502 and Z80 sections

comp_val[next_m] = comp_val[ld_ir] | comp_val[pc_pp] ; // 23-12-2024

comp_val[interrupt_m] = con6(nop, to_t, ld_ir, acc_t, reg_128, nop); // 19-6 changed from lit2 to lit128

const delay_m = comp(0, 'delay');  // a nop after IR is loaded (T<-0)
const null_m = comp(0, 'null');  // a nop. Added 10-4-2024 

// 20-7-2023 added irq_to_f to delay instruction
comp_val[delay_m] = con6(irq_to_f, to_t, xor, acc_t, lit0, nop);
comp_val[null_m] = con6(nop, to_t, xor, acc_t, lit0, nop);

// end macro's

var f_is_irq = 0;
var no_f_is_irq_error = 0;
var no_f_write_error = 0;
var no_print_cycles_upd_f_error = 0;
var did_t_upd_f = 0; // 30-11-2023
var did_f_upd_f = 0; // 30-11-2023

const pch_to_pcl = 1; // 10-11-2023 new, pch loaded from pch instead from operand bus

var comment_all = "";
var comment_t = "";
var comment_f = "";

var micro_pc = 0;
var page_default = 0;
var microcode = [];
var error_m_count = 0;

var instruction_counter = 0;

var cycle_min = 0; // for printing the number of cycles per opcode
var cycle_max = 0;
var cycles_prefix = ""; // 25-7
var micro_start = 0; // microcode start addr for this opcode
var global_idx = 0;


//------ microcode pretty-print -------

function pr_print(to_f, dst, op, src1, src2, upd) {
	comment_all = "";
	if (src2 == dir) { name2 = "(0|dpl)"; }
	else if (src2 == ext) { name2 = "(dph|dpl)"; }
	else if (src2 == ext_msb) { name2 = "(dph|dpl+1)"; }	   // 29-10-2023
	else if (src2 == pc_pp) { name2 = "(pc++)"; }
	else if (src2 == pc_lin_pp)  { name2 = "(pc_lin++)"; }	// 24-12-2024  used in blitter
	else if (src2 == pc_lin_ind) { name2 = "(pc_lin)"; }	// 24-12-2024  used in blitter	
	else if (src2 == lit0) { name2 = "0"; }
	else if (src2 == lit1) { name2 = "1"; }
	else if (src2 == lit4) { name2 = "4"; }
	else if (src2 == lit16) { name2 = "0x10"; }
	else name2 = comp_name[src2];

	if ((op == lsr) || (op == ror))
		error_msg("next line: operator not supported: " + comp_name(op)); // 15-6-2023

	// the list of one-operand instructions is also in the simulator, for the debugger.
	if ((op == inc) || (op == inc_tc) || (op == asl) || (op == rol) /* ||(op==shl_z ) */
		|| (op == shr) || (op == inc_dtc) || (op == dec_dtc)   // 29-10-2023
		|| (op == shrnew)		 // 25-6-2025
		|| (op == compl)  // 19-3-2025
		|| (op == dec) || (op == dec_1) || (op == dec_tc)) { one_operand = true; }
	else { one_operand = false; }

	if (op == ld_ir) { comment_all += "to_ir <- " + name2; }	  // 29-10-2023    
	else
		if (op == ld) {
			if (dst == to_mem) { comment_all += name2 + " <- " + comp_name[src1]; } // like reg_x <- acc_t
			else { comment_all += comp_name[dst] + " <- " + name2; } // like to_t <- (pc++)
		}
		else
			if (one_operand)  // in this case, src1 is not used, however acc_a or acc_t will be in this fields.
			{ comment_all += comp_name[dst] + " <- " + comp_name[op] + "(" + name2 + ")"; }
			else { comment_all += comp_name[dst] + " <- " + comp_name[op] + "(" + comp_name[src1] + ", " + name2 + ")"; }


	if (dst == to_pch) { comment_all = 'pcl<-pch, ' + comment_all; } // writing to pch also writes to pcl // 230529 use t // 11-11-2023 pcl<-pch

	if (op == nop)  // if op==nop, only display the first and last argument, to_f and upd. Mainly
	// used for instructions like 'next' and 'interrupt'
	{
		comment_all = "";
		if (to_f != nop) { comment_all = comp_name[to_f]; }
		if ((to_f != nop) && (dst != nop))  // is it 'next' or 'interrupt' with non-default page ?
		{ comment_all += " " + comp_name[dst]; }  // the page is in the dst argument

		if (upd != nop) { comment_all += ", " + comp_name[upd]; } // 2-11 add comma
	}
	else {
		if (to_f != nop) { comment_all += ',' + comp_name[to_f]; }  // append writing to flag_f
		if (upd != nop) { comment_all += ',' + comp_name[upd]; }  // append updating flags
	}

	if ((src1 != acc_t)&&(src1 != acc_a)) { comment_all += ", " + comp_name[src1]; } // 30-6-2024 for upd_n in v_pix_spectrum


	// now do some error checking

	//comment_all += " f_is_irq: "+f_is_irq; // debug

	if (op == ld_ir) op = ld; // ld_ir can also go together with writing to F

	if ((op != ld) && (op != inp) && (op != xor) && (to_f != delay_m) // 20-7 delay_m added
		&& (no_f_write_error == 0) && (op != compl) ) // 3-11-2023 added no_f_write_error  18-5-2025 added compl
	{
		if ((comp_val[to_f] & 0xE00000) != 0)  // if condition is specified, operation must be 'ld'.
		{
			error_msg("next line: for writing to F, operation must be 'ld', 'inp', 'compl' or 'xor'. ");
			error_msg("problem line: " + comment_all);
		}
	}

	// 22-7 new checks for cpl_c.... to do

}  // end pr_print


//------ start basic microcode building functions ------

function print_cycles() {	  // print nr of cycles of instruction

	if ((f_is_irq != 1) && (no_f_is_irq_error == 0)) error_msg("IRQ condition is not in flag F");
	no_f_is_irq_error = 0; // can be set by an opcode if it doesn't matter if IRQ condition is in flag F
	no_f_write_error = 0;

	var nr = dis_data_bytes[global_idx]; // nr of bytes in instruction

	if (cycle_max > 3)   // 3 or less, print nothing.  25-7 cycles_prefix added	  
	{
		if (cycle_min == cycle_max) { commentline("-- " + cycle_max + cycles_prefix + " cycles -- " + nr + " bytes --"); }
		else { commentline("-- " + cycle_min + "/" + cycle_max + cycles_prefix + " cycles -- " + nr + " bytes --"); }
	}
	if (cycle_max > 16) error_msg("This sequence is too long.");
	dis_data_cycles[global_idx] = cycle_max;
	cycle_min = 0; cycle_max = 0;
}

function statistics() {
	commentline("");
	commentline("-- statistics --");
	commentline("");
	var page = page_first;
	while (page <= page_last) {
		nr_of_opcodes = 0;
		var max_cycles = 0;
		var opcode = 0;
		while (opcode <= 255) {
			var idx = (page_nr[page] << 8) + opcode;
			if (dis_data_name[idx] !== undefined) {
				nr_of_opcodes++;
				if (dis_data_cycles[idx] > max_cycles) { max_cycles = dis_data_cycles[idx]; }
			}
			opcode++;
		}
		commentline("page nr " + page_nr[page] + "  " + comp_name[page] + ": "
			+ nr_of_opcodes + " opcodes, max cycles: " + max_cycles)
		page++;
	}
	var page = page_first;
	while (page <= page_last)  // print a map of the defined microcode instructions, with cycle count
	{
		var col = 0;
		var row = 0;
		commentline("");
		commentline("page nr " + page_nr[page] + "  " + comp_name[page]);
		commentline("");
		var str = "   ";
		while (col <= 15) { str += " " + hexstring2(col) + "  "; col++; }
		commentline(str);
		while (row <= 15) {
			str = hexstring2(row) + " "; col = 0; // print instruction name 
			while (col <= 15) {
				var opcode = 16 * row + col;
				var idx = (page_nr[page] << 8) + opcode;
				if (dis_data_name[idx] !== undefined) { str += (dis_data_name[idx] + "    ").substring(0, 4) + " "; }
				else str += "  -  "
				col++;
			}
			commentline(str);
			str = hexstring2(row) + " "; col = 0; // print instruction cycle count 
			while (col <= 15) {
				var opcode = 16 * row + col;
				var idx = (page_nr[page] << 8) + opcode;
				if (dis_data_name[idx] !== undefined) {
					str += hexstring2(dis_data_cycles[idx]);
					// print a star if more than 8 cycles used in this opcode 
					if (dis_data_cycles[idx] > 8) str += "*  "; else str += "   ";
				}
				else str += "  -  "
				col++;
			}
			commentline(str);
			row++;
		}
		page++;
	}

}

function opcode_page(page, opc, name, dst, src) // at the start of a new instruction, this must be called
{ // f_is_irq=0;     // 20-7    
	var prefix = " "; cycles_prefix = "";
	if (page == page_z80_ix) { prefix = "DD "; cycles_prefix = " + 2"; }
	if (page == page_z80_iy) { prefix = "FD "; cycles_prefix = " + 2"; }
	if (page == page_z80_ed) { prefix = "ED "; cycles_prefix = " + 2"; }
	if (page == page_z80_cb) {
		prefix = "CB "; cycles_prefix = " + 3";
		if ((dst == ind_hl) || (src == ind_hl)) cycles_prefix = " + 3/8";
	}
	page = page_nr[page];
	// set address in output array.
	// 29-5-2023 pagenrs are even now: 0, 2, 4 etc

	micro_pc = (page & 0xFE) << 12 | opc << 5;

	if (page & 0x01) micro_pc += 16;  // 23-3-2025 correction  25-3-2025D

	micro_start = micro_pc;

	if ((microcode[micro_pc] != undefined) && (microcode[micro_pc] !=0) ) { // 27-2-2025		
		commentline("*** ERR page: " + page + " opcode: 0x" + hexstring(opc)
			+ " Opcode already defined, it is " + hexstring(microcode[micro_pc]));
		alert("page: " + page + " opcode: 0x" + hexstring(opc) + " Opcode already defined");
	}
	// store some information for the disassembler
	current_opcode = Number(opc);
	current_page = Number(page);
	var idx = (current_page << 8) + current_opcode;
	global_idx = idx;

	//alert("index "+ idx +" page: "+current_page+" opcode:"+current_opcode  );

	dis_data_name[idx] = name; // name;
	dis_data_dst[idx] = dst;
	dis_data_src[idx] = src;
	dis_data_bytes[idx] = 1;
	dis_data_cycles[idx] = 0;

	if (name == 'JSR') dis_data_bytes[idx] = 2; // 13-11 6502 JSR contains a (pc) that should count	 

	src_string = ',' + comp_name[src]; dst_string = comp_name[dst];
	if (src == nop) { src_string = ""; }
	if (dst == nop) { dst_string = ""; }

	//commentline("");
	if (name != "!und") commentline("");	 // 27-2-2025
	commentline("---- page " + page + "  " + prefix + hexstring2(opc) + ' ' + name + ' '
		+ dst_string + src_string + " ----");
	comment_all = ""; comment_t = ""; comment_f = "";
	instruction_counter++;
	cycle_min = 0; cycle_max = 0;

	f_is_irq = 1; // 20-7-2023 The previous instruction should have done irq_to_f !

	// 30-11-2023
	did_t_upd_f = 1; did_f_upd_f = 1; // suppose upd_f was set in last instruction
	no_print_cycles_upd_f_error = 0;
}

function dis_bytes(page, addr)   // return number of bytes of instruction
{
	if (memory[addr] === undefined) return ("undefined instruction at " + hexstring(addr));

	var idx = Number((page << 8)) + memory[addr];
	bytes = dis_data_bytes[idx];
	return bytes;
}

function dis_opcode(page, opc)  // when opcode comes from a literal
{
	var idx = Number((page << 8)) + opc;
	var src = dis_data_src[idx];
	var dst = dis_data_dst[idx];
	out = dis_data_name[idx] + ' ';  // print instruction name

	if (dis_data_name[idx] != undefined) {
		if (dst != nop) out += comp_name[dst];       // print operands
		if (src != nop) out += ',' + comp_name[src];
	}
	return out;
}

function dis_text(nr, page, addr, prefix)   // disassemble this instruction, return string
{
	if (memory[addr] === undefined) return "undefined at " + hexstring(addr);
	else if (memory[addr + 1] === undefined) return "NN, undefined";
	else if (memory[addr + 2] === undefined) return "NN, NN, undefined";

	var out = hexstring2(memory[addr]) + ' ';

	var idx = Number((page << 8)) + memory[addr + nr]; // normally, nr=0. If table comes from 3rd byte, it is 2
	var bytes = dis_data_bytes[idx];

	if (nr != 0) bytes = 3; // fix for DDCB and FDCB, 3 bytes to print: CB dd NN

	var src = dis_data_src[idx];
	var dst = dis_data_dst[idx];

	if (prefix == 0xdd)   // IX
	{
		if (dst == ind_hl) dst = ind_ix_d;
		if (src == ind_hl) src = ind_ix_d;
	}
	if (prefix == 0xfd)   // IY
	{
		if (dst == ind_hl) dst = ind_iy_d;
		if (src == ind_hl) src = ind_iy_d;
	}

	if (bytes > 1) { out += hexstring2(memory[addr + 1]) + ' '; } else out += "   ";
	if (bytes > 2) { out += hexstring2(memory[addr + 2]) + ' '; } else out += "   ";
	if (bytes > 3) { out += hexstring2(memory[addr + 3]) + ' '; } else out += "   ";

	out += dis_data_name[idx] + ' ';  // print instruction name

	if (dis_data_name[idx] != undefined) {
		if (dst != nop) out += comp_name[dst];       // print operands
		if (src != nop) out += ',' + comp_name[src];
	}

	return out;
}


function opcode(val, name, mode)	// introduces the start of a new 6502 or Z80 instruction
{
	opcode_page(page_default, val, name, mode, nop);
}

function con6(a, b, c, d, e, f) {
	if ((a != nop) && (a != next_m) && (a != interrupt_m)&& (a != null_m)) f_is_irq = 0; // 20-7-2023 (240518 null_m added)

	pr_print(a, b, c, d, e, f);  		// make a nice print-out (to string: 'comment_all')

    if ((b == to_dph) && (d == acc_a)) 
	   { alert ("to_dph with ACC_A");
         error_msg ("to_dph with ACC_A");
	   }

    /* 29-10-2024 
	The microcode instructions will check if a BANK is specified. 
    - if so, specified bank is put in microcode, and NATIVE is specified (CTL_REG2 = 1)
    - if not, microcode bank is set to #3, for the case that a kernel mode is used, where it specifies the
          bank in which the kernel resides. For pure application mode it is not used (although the default 
          application bank is also bank #3)
	A bank number will only be specified as first or last argument. So only a and f need to be checked.

	But what if a register is addressed ? Or a literal ? In that case, no change is done to the opcode.

	*/
    var bsel = comp_val[bank3]; // if bank not specified, set it to #3. 

    if ((bank0 <= a) && (a <= bank7))  bsel = 4; // 4 means ctl_reg2
    if ((bank0 <= f) && (f <= bank7))  bsel = 4; // 4 means ctl_reg2	
  	if ((e == pcl)   || (e == dpl)  )  bsel = 4; // pcl, dpl own bank number, but need 'reg2' set 2-11-2024 (it's bank2)

	if (c == shr) bsel=4; // 31-10-2024 the SHR has a fixed bank nr inside it. So ctl_reg2 must be set.
	if (c == shrnew) bsel=4; // 25-6-2025 the SHR has a fixed bank nr inside it. So ctl_reg2 must be set.
	// 29-10-2024 end

	if (( e == pc_lin_pp) || ( e == pc_lin_ind) )  bsel=0; // 24-12-2024 no ctl_reg2 for pc in linear mode

	cond = comp_val[c];  // sometimes condition, but mostly instruction

	if (e == pc_pp) dis_data_bytes[(current_page << 8) + current_opcode]++; // count number of instruction bytes

	var src2 = comp_val[e];
	if ((src2 & 0xFF0000) == 0xFF0000)   // is it a register r32 - r63 ?	    
	{
		error_msg("sysreg no longer supported 19-10-2023");
		src2 = src2 & 0x00FFFF;  // clear upper FF part
		if (c != ld) error_msg("LD instruction needed for r32 - r63");
		cond = comp_val[sysreg]; // sysreg instruction
		if (comp_val[a] & 0xE00000) error_msg("r32 - r63 can not be in combination with condition");
	}

	var output = comp_val[a] | comp_val[b] | cond | comp_val[d] | src2 | comp_val[f] ;
	
    // in register mode, ctl_m1 = 1  and ctl_m0 = 0.

	if ((output & 0x000300) != 0x000200 )  // if not register mode
          output = output ^ bsel ; // 29-10-2024 added XOR bsel.

	return output;
}


function in_t(a, b, c, d, e, f) {
	comment_t = " T:[";
	val = con6(a, b, c, d, e, f);
	comment_t += comment_all + "]";
	comment_all = "";
	return val;
}
function in_f(a, b, c, d, e, f) {
	comment_f = "F:[";
	val = con6(a, b, c, d, e, f);
	comment_f += comment_all + "]";
	comment_all = "";
	return val;
}

// the if_f_t function actually writes the microcode. The operands of this function
// must be constructed with:
// "in_f(a,b,c,d,e,f)"  (first operand), and 
// "in_t(a,b,c,d,e,f)"  (second operand)
// Code in the first operand will be executed if flag F is false, and code in the second
// operand will be executed if flag F is true.

function if_f_t(instr_false, instr_true) {
	if (listing_on == 1) {
		nr = cycle_max+1; // 24-12-2024 show the seq number of the micro-instruction
		commentline(hexstring6(micro_pc) + ' ' + nr + ' ' + hexstring6(instr_false) + ' ' + hexstring6(instr_true)
			+ "  " + comment_all + comment_f + comment_t);
	}
	comment_all = ""; comment_t = ""; comment_f = "";
	
	microcode[micro_pc] = instr_false; micro_pc++; // 23-11-2023 invert ctl_m1 no more here
	microcode[micro_pc] = instr_true; micro_pc++;	 // 23-11-2023 invert ctl_m1 no more here

	if (cycle_min == 0)  // find first instruction containing 'next'.
	{
		if ((instr_false == comp_val[next_m]) || (instr_true == comp_val[next_m]))
			cycle_min = ((micro_pc - micro_start) >> 1) + 1;
	}

	cycle_max++; // keep cycle count
}

// The 'ins6' function is the main function for defining a microcode step.
// 'ins6' means: instruction with 6 components (a..f).

function ins6(a, b, c, d, e, f) {
	var value = con6(a, b, c, d, e, f);

	if_f_t(value, value); // T and F value are the same
	// 20-7 have to check for 'delay_m' and set f_is_irq
	if (a == delay_m) f_is_irq = 1; // 20-7-2023
	if (a == irq_to_f) f_is_irq = 1;  // 20-7-2023
}

// 25-7-2023
// A sequence of two microcode steps can be used to check for an interrupt. 
// It is not yet used ! (from 30-6-2024, it is)
// In this case, the flag F must already be loaded with the IRQ signal (with irq_to_f).
// The first of these two steps must be 'ins6_chi' (CHeck Interrupt ), and the
// second must be 'ins6_pcmin1' (to set PC one byte back) or
// 'ins_pcmin2' (to set PC two bytes back). The PC must be set back because
// the current instruction will be restarted after the interrupt has been handled.
// So this ins_chi thing must not be called when the instruction has already changed
// relevant registers, in such a way that changing the same registers again will give
// a wrong result. Also do not use it in an instruction that starts with toggling the CY.

// The interrupt code is located on 'page_reset' as opcode 0x05 (decimal 5, for 6502, INR6) or
// opcode 0x15 (decimal 21, for Z80, INRZ)   
// The interrupt code will do pc=pc-2.

// 21-11-2023  lit5, lit 21 no longer available
// re-introduced 15-6-2024 for Z80 only, lit32 for INRZ
function ins6_chi(a,b,c,d,e,f)		// 25-7
 { var value = in_t(a,b,c,d,e,f);

   // 30-6-2024 will now always use the Z80 instructions. should also work for 6502

   var opcode = lit32;

   // ins6_chi can not be used in the CB page, because when executing a CB instruction it
   // is not clear if an IX/IY prefix was used, so it is unclear if we must do
   // pc-2 or pc-3. Anyway, a pc-3 option is not yet available.

   if (f_is_irq==0) error_msg("next instruction, ins6_chi: The IRQ signal was not loaded into the F flag");

	// 20-9 did temp c.o.
   if_f_t(in_f(nop,to_dpl,ld_ir,acc_t,opcode,page_z80_ix),value); // F: do interrupt, T: do normal microcode step

   // 20-7 have to check for 'delay_m' and set f_is_irq
   if (a == delay_m)  f_is_irq = 1; // 20-7-2023
   if (a == irq_to_f) error_msg("irq_to_f is not allowed in ins6_chi")
 } 


function ins6_pcmin1(a, b, c, d, e, f)	// 25-7  The interrupt will do pc-2, here we do pc++
// so the actual result is pc = pc-1
{  
	// 30-6-2024 the f_is_irq must not be reset by the current pc_min1 instruction:
	if (f_is_irq == 0) error_msg("next instruction ins6_pcmin1: The IRQ signal was not loaded into the F flag")
 	var value = in_t(a, b, c, d, e, f);

	// 20-9 did temp co
	if_f_t(in_f(nop, to_dpl, ld, acc_t, pc_pp, nop), value); // F: add one to pc T: regular microcode

	// 19-7-2024 compensate count number of instruction bytes, was incremented by previous pc_pp:
	dis_data_bytes[(current_page << 8) + current_opcode]--; 

	// 20-7 have to check for 'delay_m' and set f_is_irq
	if (a == delay_m) f_is_irq = 1; // 20-7-2023
	if (a == irq_to_f) f_is_irq = 1;  // 20-7-2023
}

function ins6_pcmin2(a, b, c, d, e, f)	// 25-7  The interrupt will do pc-2, no action here
{  
	// 30-6-2024 the f_is_irq must not be reset by the current pc_min2 instruction:
	if (f_is_irq == 0) error_msg("next instruction ins6_pcmin2: The IRQ signal was not loaded into the F flag")
	var value = in_t(a, b, c, d, e, f);

    // 20-9 did temp co
	if_f_t(in_f(nop, to_dpl, ld, acc_t, lit0, nop), value); // F: no action T: regular microcode

	// 20-7 have to check for 'delay_m' and set f_is_irq
	if (a == delay_m) f_is_irq = 1; // 20-7-2023
	if (a == irq_to_f) f_is_irq = 1;  // 20-7-2023
}

// 'final' will be used at the end of an instruction sequence. It will:
// When flag F does not indicate interrupt, place two instructions:
//   1. The 'next' instruction
//   2. The indicated (a,b,c,d,e,f) instruction (in the 'delay' slot).
//
// But when F indicates an interrupt, the instructions will be split in a part executed
// when F = 0 (indicated by false: F:[...] ) and a part executed when F = 1 (indicated by true: T:[...] ).
//
// If flag F is 1, the interrupt is not active, and the 'True' part of the instructions are executed:
//   1. T: [ The 'next' instruction ]
//   2. T: [ The indicated (a,b,c,d,e,f) instruction (in the 'delay' slot).]
//
// When flag F is 0, the interrupt is active, and the following is executed:
//   1. F: [ The 'interrupt' instruction ]
//   2. F: [ The indicated (a,b,c,d,e,f) instruction ]

// 'c' contains the operation. If that needs a condition (carry input) that condition
// must be selected in the 'next' instruction that precedes it.

// if an active interrupt signal is detected, the interrupt will be handled, and after 
// the interrupt, processing will continue with the next instruction.

function final(a, b, c, d, e, f) {
	var cond = nop;
	if (f_is_irq)// flag F indicates interrupt
	{
		if_f_t(in_f(interrupt_m, nop, cond, nop, nop, nop), // interrupt when active (low)
			in_t(next_m, nop, cond, nop, nop, nop));    // next instruction when not active (high)
		ins6(a, b, c, d, e, f);
	}
	else  // flag doesnt indicate interrupt
	{
		ins6(next_m, nop, cond, nop, nop, nop);
		ins6(a, b, c, d, e, f);
	}
}


//------ generation of  constants  -----------


function make_bitmask(dst, bitnr)  // place a mask 00000001 - 10000000 in the dst 
{
	if      (bitnr == 0) { ins6(nop, dst, inc, acc_t, lit0, nop); }  // 00000001 increment a zero-value	  
	else if (bitnr == 1) { ins6(nop, dst, inc, acc_t, lit1, nop); }  // 00000010 0x02 value 1 incr  26-6	  
	else if (bitnr == 2) { ins6(nop, dst, ld, acc_t, lit4, nop); }   // 00000100 value 4
	else if (bitnr == 3) { ins6(nop, dst, asl, acc_t, lit4, nop); }  // 00001000 value 4 shifted left          
	else if (bitnr == 4) { ins6(nop, dst, ld, acc_t, lit16, nop); }  // 00010000 value 16
	else if (bitnr == 5) { ins6(nop, dst, asl, acc_t, lit16, nop); } // 00100000 value 16 shifted left		  
	else if (bitnr == 6) { ins6(nop, dst, asl, acc_t, lit32, nop); } // 01000000 value 32 shifted left 7-9-2023
	else if (bitnr == 7) { ins6(nop, dst, ld, acc_t, reg_128, nop); }// 10000000 value 128 7-9-2023
	else { error_msg("invalid bit number"); }
}

function make_nr(dst, nr)   // put an 8-bit number in dst, using a single cycle. Used for extension opcodes.
{
	if (nr == 0) { ins6(nop, dst, ld, acc_t, lit0, nop); }         // 00000000 0x00 
	else if (nr == 1) { ins6(nop, dst, inc, acc_t, lit0, nop); }   // 00000001 0x01 increment a zero-value	  
	else if (nr == 2) { ins6(nop, dst, inc, acc_t, lit1, nop); }   // 00000010 0x02 value 1 incr
	else if (nr == 3) { ins6(nop, dst, shl_1, acc_t, lit1, nop); } // 00000011 0x03 value 1 shl+cy
	else if (nr == 4) { ins6(nop, dst, ld, acc_t, lit4, nop); }    // 00000100 0x04 value 4
	else if (nr == 5) { ins6(nop, dst, inc, acc_t, lit4, nop); }   // 00000101 0x05 value 4 incr

	else if (nr == 0x14) { ins6(nop, dst, ld, acc_t, lit20, nop); } // 00010100 0x14 value 16 + 4

	else { error_msg("make_nr: invalid number: " + nr); }
}

// 2-10-2024 generate code to put an 8-bit number in dst (must be to_t or to_a). Used for microcode date reporting, and HLT.
function make_literal(dst, nr)  
{ 	if (dst==to_a) src = acc_a 
  	else if (dst==to_t) src = acc_t
  	else { error_msg("make_literal: invalid destination, must be to_t or to_a: "); }

    var opcode = ld;
	n29 = nr & 0x29; // bits  0010 1001
  	n52 = nr & 0x52; // bits  0101 0010  ( 0x29 shifted left)
  	n04 = nr & 0x04; // bits  0000 0100
  	n80 = nr & 0x80; // bits  1000 0000

	// several optimizations will be possible, not really needed now.
	// - when n29=1, can be done with extra increment in another instruction
	// - value FF can be just dec(0)
	// - value 4 might be combined with value 16 to a single shift-right group

	// For using it for color conversion in BLIT24, need to do it in 3 cycles max.
	// Only need a 0x84 (decimal 132)
	// But.. we want a value 0-15 in a single instruction. Use extra value 0x0C. And 0x0F that already present.
	// And note that this lower nibble must be OR'ed to another value... 
	// And need upper nibble. May take two cycles. Need value 0xA0 to make this range complete.

	// But, if BLIT24 uses black and 3 colors, then need 6 regs (if 0 is black),(3 low nibble, 3 high nibble). In that
	// case, don't need 0x84, or 0x0C and 0xA0.

    // shortcuts
    if (nr == 255)
	  { ins6(nop, dst, dec, src, lit0, nop); // LD with FF
	    return;
	  }	 

    // end shortcuts
	if (n52 != 0 )
	  { n52 = n52 >> 1;
 		if (n52==1)  literal = lit1;
	    if (n52==8)  literal = lit8;
	    if (n52==32) literal = lit32;				
	    if (n52==9)  literal = lit9;
	    if (n52==33) literal = lit33;
	    if (n52==40) literal = lit40;				
	    if (n52==41) literal = lit41;	  
 		ins6(nop, dst, asl, src, literal, nop); // dst <- ASL bits 00x0 x00x
		opcode = or;
	  }
    if (n29 != 0)
	  { if (n29==1)  literal = lit1;
	    if (n29==8)  literal = lit8;
	    if (n29==32) literal = lit32;				
	    if (n29==9)  literal = lit9;
	    if (n29==33) literal = lit33;
	    if (n29==40) literal = lit40;				
	    if (n29==41) literal = lit41;
	    ins6(nop, dst, opcode, src, literal, nop); // LD/OR bits 00x0 x00x
		opcode = or;
	  }
    if (n04 != 0)
	  { ins6(nop, dst, opcode, src, lit4, nop); // LD/OR bits 0000 0100
		opcode = or;
	  }
    if (n80 != 0)
	  { ins6(nop, dst, opcode, src, reg_128, nop); // LD/OR bits 1000 0000
		opcode = or;
	  }	  
    if (nr == 0)
	  { ins6(nop, dst, ld, src, lit0, nop); // LD with zero
	  }	  
}

//------ end of basic microcode building functions -----------


// 2-10-2024 generate code to put an 8-bit number in dst (must be to_t or to_a). Used for microcode date reporting, and HLT.
// 27-2-2025 copy of this code, for use in undefined opcodes
function make_literal_new(dst, nr)  
{ 	if (dst==to_a) src = acc_a 
  	else if (dst==to_t) src = acc_t
  	else { error_msg("make_literal_new: invalid destination, must be to_t or to_a: "); }

    var opcode = ld;
	n29 = nr & 0x29; // bits  0010 1001
  	n52 = nr & 0x52; // bits  0101 0010  ( 0x29 shifted left)
  	n04 = nr & 0x04; // bits  0000 0100
  	n80 = nr & 0x80; // bits  1000 0000

	// several optimizations will be possible.
	// - when n29=1, can be done with extra increment in another instruction
	// - value FF can be just dec(0)
	// - value 4 might be combined with value 16 to a single shift-right group

	if ((n04 != 0) && (n52 == 16))  // - value 4 might be combined with value 16 to a single shift-right group
	  { n52 = 0; n04=0;
	    opcode = ld;  
		if (n29 == 1)
		  { opcode = inc; n29=0; } 
        ins6(nop, dst, opcode, src, lit20, nop);
		opcode = add;
	  }

	// For using it for color conversion in BLIT24, need to do it in 3 cycles max.
	// Only need a 0x84 (decimal 132)
	// But.. we want a value 0-15 in a single instruction. Use extra value 0x0C. And 0x0F that already present.
	// And note that this lower nibble must be OR'ed to another value... 
	// And need upper nibble. May take two cycles. Need value 0xA0 to make this range complete.

	// But, if BLIT24 uses black and 3 colors, then need 6 regs (if 0 is black),(3 low nibble, 3 high nibble). In that
	// case, don't need 0x84, or 0x0C and 0xA0.

    // shortcuts
    if (nr == 255)
	  { ins6(nop, dst, dec, src, lit0, nop); // LD with FF
	    return;
	  }	 

    // end shortcuts
	if (n52 != 0 )
	  { n52 = n52 >> 1;
 		if (n52==1)  literal = lit1;
	    if (n52==8)  literal = lit8;
	    if (n52==32) literal = lit32;				
	    if (n52==9)  literal = lit9;
	    if (n52==33) literal = lit33;
	    if (n52==40) literal = lit40;				
	    if (n52==41) literal = lit41;	
		opcode = asl;  
		if (n29 == 1)
		  { opcode = shl_1; n29=0; } 
 		ins6(nop, dst, opcode, src, literal, nop); // dst <- ASL bits 00x0 x00x
		opcode = add;
	  }
    if (n04 != 0)
	  { ins6(nop, dst, opcode, src, lit4, nop); // LD/ADD bits 0000 0x00
		opcode = add;
	  }
    if (n80 != 0)
	  { ins6(nop, dst, opcode, src, reg_128, nop); // LD/ADD bits x000 0000
		opcode = add;
	  }	  
    if (n29 != 0)
	  { if (n29==1)  literal = lit1;
	    if (n29==8)  literal = lit8;
	    if (n29==32) literal = lit32;				
	    if (n29==9)  literal = lit9;
	    if (n29==33) literal = lit33;
	    if (n29==40) literal = lit40;				
	    if (n29==41) literal = lit41;
	    ins6(nop, dst, opcode, src, literal, nop); // LD/OR bits 00x0 x00x
		opcode = add;
	  }
    if (nr == 0)
	  { ins6(nop, dst, ld, src, lit0, nop); // LD with zero
	  }	  
}

//------ functions to generate nibble-sized constants  -----------

// 19-3-2025

/* usage:
  // the prepare function (use the high or low version) doesn't generate code
  nibble_prep( dst, add/ld, src, val(0-15), 16)  // generated high nibble: prepares: nibble_dst, nibble_1_opc, nibble_1_lit, nibble_src
  nibble_prep( dst, add/ld, src, val(0-15), 1)   // generate low nibble

  // the code will be generated by the next 3 functions (all three must be used)
  nibble_1(); // generates three instructions (or less).
  nibble_2(); // between nibble 2 and 3, a jump can be placed, so nibble 3 is done in the delay slot.
  nibble_3();
*/
  
  var nibble_1_opc, nibble_1_lit
  var nibble_2_opc, nibble_2_lit
  var nibble_3_opc, nibble_3_lit
  var nibble_dst, nibble_src, nibble_shift, nibble_mode

  function nibble_1()  
    { if (nibble_1_opc != nop) ins6( nop, nibble_dst, nibble_1_opc, nibble_src, nibble_1_lit, nop); }
  function nibble_2()  
    { if (nibble_2_opc != nop) ins6( nop, nibble_dst, nibble_2_opc, nibble_src, nibble_2_lit, nop); }
  function nibble_3() 
    { if (nibble_3_opc != nop) ins6( nop, nibble_dst, nibble_3_opc, nibble_src, nibble_3_lit, nop); }

 function nibble_make( nr, val )
   { var op;
     var literal;
     if (nibble_mode == ld)
       switch (val) {
          case 0:  { op= ld; literal = lit0; break;  } 
          case 1:  { op= ld; literal = lit1; break;  }
          case 2:  { op= inc; literal = lit1; break;  }
          case 8:  { op= ld; literal = lit8; break;  }
          case 15: { op= ld; literal = reg_0F; break;  }
          case 16:  { op= ld; literal = lit16; break;  }
          case 32:  { op= ld; literal = lit32; break;  }
          case 128: { op= ld; literal = reg_128; break;  }
          case 240: { op= compl ; literal = reg_0F; break;  }  // load complement. New ALU instruction !
          default:  { error_msg("nibble_make/ld: invalid value " +val); } 
          }
     else // mode == add
       switch (val) {
          case 0:  { op= add;   literal = lit0; break; }
          case 1:  { op= add;   literal = lit1; break;  }
          case 2:  { op= add_1; literal = lit1; break;  }
          case 8:  { op= add;   literal = lit8; break;  }
          case 15: { op= add;   literal = reg_0F; break;  }
		  case -1: { op= sub;   literal = lit1; break;  } 
          case -2: { op= sub_0; literal = lit1; break;  } 
          case -8: { op= sub;   literal = lit8; break;  }
         
		  case 16:  { op= add;   literal = lit16; break;   }		  
          case 32:  { op= add;   literal = lit32; break;    }
          case 128: { op= add;   literal = reg_128; break;  }
          case 240: { op= sub_0; literal = reg_0F; break;   } 

		  case -16:  { op= sub; literal = lit16; break;   } 
          case -32:  { op= sub; literal = lit32; break;    }
          case -128: { op= sub; literal = reg_128; break;  }
          default: { error_msg("nibble_make/add: invalid value "+ val); }
          }
     // "leading 0 suppression"
	 
     if ((val == 0) && (nr != 3)) op = nop;

     if (nr==1) { nibble_1_opc = op ; nibble_1_lit = literal }
     if (nr==2) { nibble_2_opc = op ; nibble_2_lit = literal }
     if (nr==3) { nibble_3_opc = op ; nibble_3_lit = literal }

     if (op != nop) nibble_mode = add;  // next instructions will always add/sub. (unless nothing generated here)
	 
   }

  function nibble_gen(v1, v2, v3)
    { nibble_make(1, nibble_shift * v1);
      nibble_make(2, nibble_shift * v2);
      nibble_make(3, nibble_shift * v3);
    }

  function nibble_prep( dst, mode, src, value, shift )
    { nibble_dst = dst; nibble_src = src; // src and dst should be same register
      nibble_mode = mode; // for first nibble, selects add or ld, then becomes add.
      nibble_shift = shift // 1 for low byte, 16 for high byte.
      switch (value) { 
       case 0: nibble_gen( 0, 0, 0); break;
       case 1: nibble_gen( 0, 0, 1); break;
       case 2: nibble_gen( 0, 0, 2); break;
       case 3: nibble_gen( 0, 1, 2); break;
       case 4: nibble_gen( 0, 2, 2); break;
       case 5: nibble_gen( 1, 2, 2); break;
       case 6: nibble_gen( 0, 8, -2); break;
       case 7: nibble_gen( 0, 8, -1); break;
       case 8: nibble_gen( 0, 0, 8); break;
       case 9: nibble_gen( 0, 8, 1); break;
      case 10: nibble_gen( 0, 8, 2); break;
      case 11: nibble_gen( 8, 2, 1); break;
      case 12: nibble_gen( 8, 2, 2); break;  
      case 13: nibble_gen( 0, 15, -2); break;
      case 14: nibble_gen( 0, 15, -1); break;  
      case 15: nibble_gen( 0, 0, 15); break;
      default: { error_msg("nibble_prep: invalid value "); } 
      // Numbers built from: 0, 1, 2, 8, 15, -1, -2, -8 
      } 
    }

const BINC = lit41;
const opc_binc = 0x29;

/*
Isetta colors:
0  black
1  blue
2  green
3  cyan
4  red
5  magenta
6  yellow
7  white
15 gray
8  dark  // add this to the basic color number to get a dark version

SymbOs colors:
0  light yellow (or transparent)
1  black                        
2  orange
3  dark red
4  cyan
5  dark blue                    
6  light blue 
7  blue
8  white
9  dark green
10 green
11 magenta
12 yellow
13 gray
14 light red
15 red
*/

const color_table = [6, 0, 4, 8+4, 3, 8+1, 3, 1, 7, 8+2, 2, 5, 6, 15, 5, 4 ];
//                   ^     ^               ^                          ^
// Indicated colors are light yellow, orange, light blue, light red that can not exactly be converted.


function make_color_conversion()  // new 20-3-2025
  { opc = 0;
    while (opc <= 255)
	  { 

		var high = (opc >> 4) & 0x0F;
		var low  = opc & 0x0F;
        var newhigh = color_table[high];
        var newlow  = color_table[low];	
		var newbyte = 16*newhigh + newlow;	

		opcode_page(page_copycnv, opc, "CPYCNV to "+hexstring2(newbyte), nop, nop);

		ins6(tc_to_f,to_t,xor, acc_t,lit0,nop); // nop, tc_to_f for CY of preceding inc DPL

		if ((high==0) && (low==0)) commentline("-- both nibbles transparent --  ")
		else
        if (high==0)
		  {  commentline("-- high nibble transparent --  ");
		     ins6(nop,to_t,res2, acc_t,reg_0F,nop);  // clear low nibble
             nibble_prep( to_t, add, acc_t, newlow, 1 );
			 nibble_1();
			 nibble_2();
			 nibble_3();
		  }
		else
        if (low==0)
		  {  commentline("-- low nibble transparent --  ");
		     ins6(nop,to_t,and, acc_t,reg_0F,nop);  // clear high nibble
             nibble_prep( to_t, add, acc_t, newhigh, 16 );
			 nibble_1();
			 nibble_2();
			 nibble_3();
		  }
        else
			make_literal_new(to_t,newbyte);

		//  F0: inc DPL had no CY. back to loop.    F1: inc DPL had CY. jump to BINC that will increment DPH

		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label2, page_blit), in_t(nop, to_t, ld_ir, acc_t, lit41, page_blit)); 

		ins6(irq_to_f,to_mem,ld, acc_t,pc_lin_pp,nop);  // store T at (pc++)
		opc++;
	  }

   // 25-3-2025D  add generation for unaligned

 opc = 0;
    while (opc <= 255)  // for unaligned bytes
          {
                var high = (opc >> 4) & 0x0F;
                var low  = opc & 0x0F;
        var newhigh = color_table[high];
        var newlow  = color_table[low];        
                var newbyte = 16*newhigh + newlow;        
                opcode_page(page_copycnv_un, opc, "CPYCNV_UNALIGNED to "+hexstring2(newbyte), nop, nop);
        if (high==0)
                  {  commentline("-- high nibble can be transparent --  "); // color 0 is in fill_1 (low nibble)
                     // high nibble: F=0 transparent     F=1 OR color 0   result to low nibble
                         //              T <- (pc)
                         //              T <- T and 0F
                         //              T <- T or t_save_t  
                        if_f_t(in_f(nop, to_t, ld, acc_t, pc_lin_ind, nop), in_t(nop,to_t,or,acc_t,fill_1,nop));
                        if_f_t(in_f(nop, to_t, and, acc_t, reg_0F, nop),    in_t(nop,to_t,or,acc_t,lit0,nop));
                        if_f_t(in_f(nop, to_t, or, acc_t, t_save_t, nop),   in_t(nop,to_t,or,acc_t,lit0,nop));
                  }
                else // high nibble non-transparent
                  {  
             nibble_prep( to_t, add, acc_t, newhigh, 1 );  // high nibble convert, to low nibble
                         nibble_1();  // 3 cycles max.
                         nibble_2();
                         nibble_3();
                  }          
                
        if (low==0)
                  {  commentline("-- low nibble can be transparent --  ");   // color 0 = t_fill_1_s4 (high nibble)
                          ins6(nop,to_mem,ld, acc_t,pc_lin_pp,nop);  // (pc++) <- T
                     // high nibble: F=0 transparent     F=1 OR color 0   result to high nibble
                         //              T <- (pc)                 T <- 0xF0 // color 0
                         // F <- C
                         // jump
                         //              T <- T and F0             T <- T and F0 (useless)
                        
                        if_f_t(in_f(nop, to_t, ld, acc_t, pc_lin_ind, nop), in_t(nop,to_t,ld,acc_t,t_fill_1_sh4,nop));
                        ins6(c_to_f,to_t,xor, acc_t,lit0,nop);  // F <- c, nop
                        //  F0: inc DPL had no CY. back to loop.    F1: inc DPL had CY. jump to BINC that will increment DPH
                        if_f_t(in_f(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit), in_t(irq_to_f, to_t, ld_ir, acc_t, lit41, page_blit));                    
                    ins6(nop, to_t, res2, acc_t, reg_0F, nop);
                  }
        else // low nibble non-transparent
                  { ins6(c_to_f,to_mem,ld, acc_t,pc_lin_pp,nop);  // (pc++) <- T, F <- c
             		nibble_prep( to_t, ld, acc_t, newlow, 16 );
                    nibble_1();
                    nibble_2();
                    //  F0: inc DPL had no CY. back to loop.    F1: inc DPL had CY. jump to BINC that will increment DPH
                    if_f_t(in_f(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit), in_t(irq_to_f, to_t, ld_ir, acc_t, lit41, page_blit));
                    nibble_3();
                  }
                opc++;
          }             
  }



function make_cp_u_table()  // new 9-4-2025
  { 
   //   add generation for unaligned. No color conversion, no transparency.

 	opc = 0;
    while (opc <= 255)  // for unaligned bytes
          {
            var high = (opc >> 4) & 0x0F;
            var low  = opc & 0x0F;			               
            opcode_page(page_cp_u, opc, "CP_UNALIGNED", nop, nop);
			// high nibble non-transparent
            {   nibble_prep( to_t, add, acc_t, high, 1 );  // high nibble convert, to low nibble
                nibble_1();  // 3 cycles max.
                nibble_2();
                nibble_3();
            }          
  			// low nibble non-transparent
            {   ins6(c_to_f,to_mem,ld, acc_t,pc_lin_pp,nop);  // (pc++) <- T, F <- c
             	nibble_prep( to_t, ld, acc_t, low, 16 );
                nibble_1();
                nibble_2();
                //  F0: inc DPL had no CY. back to loop.    F1: inc DPL had CY. jump to BINC that will increment DPH
                if_f_t(in_f(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit), in_t(irq_to_f, to_t, ld_ir, acc_t, lit41, page_blit));
                nibble_3();
            }
            opc++;
          }             
  }


//------ end of nibble-sized constants  -----------

// 27-2-2025  Handling of undefined opcodes  "UNDEF"

function isetta_undef(page,from,to)
 { 	var opc=from;
	while (opc <= to)
	 { opcode_page(page, opc, "=", nop, nop); //   "=" means, undefined instruction
	   // the first word is 000000
	   // This is used as a valid code to be overwritten by a real instruction.
	   // However, to the Isetta it will appear as FFFFFF, because
	   // the programmer will not program 000000 values, so the location stays erased.
	   // FFFFFF will write something to output, and do irq_to_f and perhaps
	   // something else, that won't matter for an emergency like this.
	   comment_all = "erased, FFFFFF"
	   if_f_t(0, 0); // this makes 000000	

       listing_on = 0;
	   // Now, it will place the opcode in T
	   // and a code for the page in dpl
       if ( (opc & 0x84) == 0x84 )  // if bit 2 and 7 both set
	     { make_literal_new(to_t, opc & 0x7B); // reset bits 0x84
	       ins6(nop, to_t, ld_ir, acc_t, reg_0F, page_z80_ix);  // jp to opcode 0F in page IX, that will add bits 2 and 7
		 }
	   else 
	     { make_literal_new(to_t, opc); 
	       ins6(nop, to_t, ld_ir, acc_t, reg_0F, page_reset);  // jp to opcode 0F in page 0
		 }
       var mycode = nop;
	   var page_report =lit40; // 40 = unknown
	   if (page == page_reset)   { page_report = lit0; mycode = ld; }  // 0
	   if (page == page_6502)    { page_report = lit1; mycode = inc; } // 2	   
	   if (page == page_z80)     { page_report = lit4; mycode = ld; }  // 4
	   if (page == page_z80_ix)  { page_report = lit32; mycode = ld; } // 6 -> dec 32
	   if (page == page_z80_cb)  { page_report = lit8; mycode = ld; }  // 8 
	   if (page == page_z80_iy)  { page_report = lit33; mycode = ld; } // 10 -> dec 33	
	   if (page == page_hires)   { page_report = lit20; mycode = ld; } // 20   

	   ins6(nop, to_dpl, mycode, acc_t, page_report, nop);  // put the page in dpl  
       listing_on = 1;	   

	   opc++;	
	 }
 }


// execution jumps to following function if an undefined microinstruction is encountered
// It stores a lot of information about the crashed program.
// That information can be retrieved by a diagniostics program DIAGN.BIN, after the next reset.

function handle_undef(opc, myname)  // opcode 0F in page_reset. UNDEF.
 { 
	opcode_page(page_reset, opc, myname, nop, nop);
    // opcode will be in T. Page code in dpl.

	ins6(nop, to_mem, ld, acc_t, save_opcode, nop); // store T (opcode)
    ins6(nop, to_t, ld, acc_t, dpl, nop);  // get dpl (page) to T
	ins6(nop, to_mem, ld, acc_t, save_page, nop); // store T (page)
	ins6(nop, to_mem, ld, acc_a, save_acc, nop); // store ACC

    // put PC somewhere
    ins6(nop, to_dpl, ld, acc_t, lit16, nop);   // let dph/dpl point to 0510 (bank0)
    ins6(nop, to_dph, inc, acc_t, lit4, nop); 

	ins6(nop, to_t, ld, acc_t, pcl, nop); // get pcl
	ins6(nop, to_mem, ld, acc_t, ext, bank0); // at 0510  store pcl

	ins6(nop, to_pch, ld, acc_t, lit0, nop);  // write to pch to put it in pcl
	ins6(nop, to_t, ld, acc_t, dpl, nop); // get pch
	ins6(nop, to_mem, ld, acc_t, ext_msb, bank0); // at 0511  store pch

    ins6(nop, to_t, shl_1, acc_t, reg_0F, nop); //value 1F to dpl
	ins6(nop, to_mem, ld, acc_t, reg_kb_tmp, nop) // store it, used as jp address for UNCPY

    ins6(nop, to_t, ld_ir, acc_t, reg_kb_tmp, page_reset);  // jp to opcode 1F in page 0, for copying registers
    ins6(nop, to_dpl, zero, acc_t, lit0, nop); // dpl <-0  prepare copying registers
	print_cycles();


	opcode_page(page_reset, 0x1F, "UNCPY", nop, nop); // copy all 256 registers. opcode 1F in page_reset.

    ins6(nop, to_dph, zero, acc_t, lit0, nop); // source addr MSB: 0
	ins6(nop, to_t, ld, acc_t, ext, bank0); // data get from 00xx bank0	
    ins6(nop, to_dph, inc, acc_t, lit8, nop); // dest addr MSB: 9
	ins6(nop, to_mem, ld, acc_t, ext, bank1); // store at 09xx bank1

    ins6(nop, to_dpl, inc, acc_t, dpl, nop);  // next addr
    ins6(tc_to_f, to_t, ld, acc_t, lit0, nop); // nop, tc -> F
    // F=0  repeat               F=1, the end is reached
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, reg_kb_tmp, page_reset),in_t(nop, to_t, xor, acc_t, lit0, nop) ); 
	ins6(nop, to_t, ld, acc_t, lit33, nop); // get magic number 33 (in delay)

    ins6(nop, to_dpl, dec, acc_t, reg_0F, nop);   // let dph/dpl point to 050E (bank0)
    ins6(nop, to_dph, inc, acc_t, lit4, nop); 	
  
	ins6(nop, to_mem, ld, acc_t, ext, bank0); // at 050E  store 33
	ins6(nop, to_t, inc, acc_t, reg_128, nop); // get magic number 129
	ins6(nop, to_mem, ld, acc_t, ext_msb, bank0); // at 050F  store 129

    ins6(nop, to_dpl, asl, acc_t, lit40, nop); //value 80 (0x50) to dpl
    ins6(nop, to_t, ld_ir, acc_t, dpl, page_z80_ix);  // jump to HANG
    ins6(nop, to_t, ld, acc_t, lit0, nop); // nop
	print_cycles(); 



	opcode_page(page_z80_ix, 0x50, "HANG", nop, nop); // opcode 0x50 in page_z80_ix
    // Allow interrupt, to show the screen, but everything is freezed. Waiting for a reset.
	// Note that this instruction can be longer than 16 cycles.
    // first put an indication on the Hires screen, at lower right corner (four green pixels)
    ins6(nop, to_dpl, ld, acc_t, reg_128, nop);   // let dph/dpl point to FF80
    ins6(nop, to_dph, dec, acc_t, lit0, nop);	
	make_literal_new(to_t, 0x22);  // two green pixels
    ins6(nop, to_mem, ld, acc_t, ext,     bank2);  // place 2 pixels, on lower screen half, lowest line
	ins6(nop, to_mem, ld, acc_t, ext_msb, bank2);  // another two pixels

    ins6(nop, to_dpl, ld, acc_t, lit4, nop);   // let dph/dpl point to 0004
    ins6(nop, to_dph, ld, acc_t, lit0, nop);
	make_literal_new(to_t, 0xc3); // JP  (note that JR does not test interrupts)
    ins6(nop, to_mem, ld, acc_t, ext, nop); // place JP at 0000
    ins6(nop, to_dpl, inc, acc_t, dpl, nop);	 // inc dpl	
	make_literal_new(to_t, 0x04); // 
    ins6(nop, to_mem, ld, acc_t, ext, nop);	// place instruction at 0004: JP to 0004. endless loop.
    ins6(nop, to_dpl, inc, acc_t, dpl, nop);	 // inc dpl
	make_literal_new(to_t, 0x00); // 
    ins6(nop, to_mem, ld, acc_t, ext, nop);	// msb of 0004

	make_literal_new(to_t, ISA_Z80); 	
	ins6(irq_to_f, to_mem, ld, acc_t, reg_isa, nop); // set processor to Z80
    ins6(nop, to_pch, ld, acc_t, lit4, nop);
    ins6(nop, to_pch, ld, acc_t, lit0, nop); // pc = 0004	
    ins6(nop, to_t, ld_ir, acc_t, pc_pp, page_z80); // jp to the instruction
    ins6(nop, to_t, ld, acc_t, lit0, nop); // nop
	print_cycles();	

	// in page_z80_ix, bit2 and bit7 are added, and then it jumps to 0F in page_reset
	opcode_page(page_z80_ix, opc, "UN27", nop, nop); // opcode 0F in page_z80_ix
    // opcode will be in T. Page code in dpl.
    ins6(nop, to_t, add, acc_t, lit4, nop);
    ins6(nop, to_t, ld_ir, acc_t, reg_0F, page_reset);
    ins6(nop, to_t, add, acc_t, reg_128, nop);
	print_cycles();
 }


//-----------------------------------------------------

//	6502 functions

//----------------------------------------------------

function addrmode(mode) { // this might also put irq in F
	// should give error if mode== reg_a  
	if (mode == imm) {
		return pc_pp;
	}
	if (mode == zp) {
		ins6(irq_to_f, to_dpl, ld, acc_a, pc_pp, nop); // get zp addr to dpl
		return dir; // use 0/dpl as operand address (6800 direct addressing)
	}
	if (mode == zpx) {
		ins6(irq_to_f, to_t, ld, acc_a, pc_pp, nop); // get zp addr to t
		ins6(nop, to_dpl, add, acc_t, reg_x, nop);  // add reg x to t, result in dpl
		commentline("---- end of ea calculation ---");
		return dir; // use 0/dpl as operand address (6800 direct addressing)
	}
	if (mode == zpy) {
		ins6(irq_to_f, to_t, ld, acc_a, pc_pp, nop); // get zp addr to t
		ins6(nop, to_dpl, add, acc_t, reg_y, nop);  // add reg y to t, result in dpl
		commentline("---- end of ea calculation ---");
		return dir; // use 0/dpl as operand address (6800 direct addressing)
	}
	if (mode == abs) {
		ins6(irq_to_f, to_dpl, ld, acc_a, pc_pp, nop); // get low addr to dpl
		ins6(nop, to_dph, ld, acc_t, pc_pp, nop); // get high addr to dph // 29-10-2024 change acc_a to acc_t
		commentline("---- end of ea calculation ---");
		return ext; // use dph/dpl as operand address(z80 extended addressing)
	}
	if (mode == absx) {
		ins6(irq_to_f, to_t, ld, acc_a, pc_pp, nop); // get low addr to t	     
		ins6(nop, to_dpl, add, acc_t, reg_x, nop);  // add reg x to t, result in dpl
		ins6(nop, to_dph, inc_tc, acc_t, pc_pp, nop); // inc high addr if TC set // 29-10-2024 change acc_a to acc_t
		commentline("---- end of ea calculation ---");
		return ext; // use dph/dpl as operand address(z80 extended addressing)
	}
	if (mode == absy) {
		ins6(irq_to_f, to_t, ld, acc_a, pc_pp, nop); // get low addr to t
		ins6(nop, to_dpl, add, acc_t, reg_y, nop);  // add reg y to t, result in dpl
		ins6(nop, to_dph, inc_tc, acc_t, pc_pp, nop); // inc high addr if TC set // 29-10-2024 change acc_a to acc_t
		commentline("---- end of ea calculation ---");
		return ext; // use dph/dpl as operand address(z80 extended addressing)
	}
	if (mode == idx) // idx_indexed_indirect
	{ 
		ins6(irq_to_f, to_t, ld, acc_a, pc_pp, nop); // 30-11 get low addr to t 
		ins6(nop, to_dpl, add, acc_t, reg_x, nop);  // add reg x to t, result in dpl
		ins6(nop, to_t, ld, acc_a, dir, nop); // get final low addr to t, direct mode
		ins6(nop, to_dpl, inc, acc_a, dpl, nop); // inc addr in zpage to access high addr
		ins6(nop, to_dph, ld, acc_t, dir, nop); // 30-11 get final high addr in dph  21-7 irq // 29-10-2024 change acc_a to acc_t
		ins6(nop, to_dpl, add, acc_t, lit0, nop);    // move low addr from T to dpl (by adding zero)
		commentline("---- end of ea calculation ---");
		return ext; // use dph/dpl as operand address(z80 extended addressing)
	}
	if (mode == idy) // idy_indirect_indexed
	{ 
		ins6(irq_to_f, to_dpl, ld, acc_a, pc_pp, nop); // 30-11 get zp addr to dpl

		ins6(nop, to_t, ld, acc_a, dir, nop);  // low addr to t
		ins6(nop, to_dpl, inc, acc_a, dpl, nop); // inc addr in zpage to access high addr	
		// 9-11-2023
		ins6(nop, to_t, add, acc_t, reg_y, nop);  // add reg y to t, result in t
		ins6(nop, to_dph, inc_tc, acc_t, dir, nop); // get high addr to dph, with TC added // 29-10-2024 change acc_a to acc_t
		
		ins6(nop, to_dpl, xor, acc_t, lit0, nop);  // 30-11 dpl <- T

		commentline("---- end of ea calculation ---");
		return ext; // use dph/dpl as operand address(z80 extended addressing)
	}
	if (mode == reg_x) {
		return reg_x; // use reg_x as operand, used for TXA TAX INX DEX
	}
	if (mode == reg_y) {
		return reg_y; // use reg_y as operand, used for TYA TAY INY DEY
	}

	error_msg("addressing mode unknown: " + comp_name[mode]);
	return error;  // dir, ext, reg_xx, (an imm comes in dph or dpl)  TODO
}

// LDA LDX LDY TXA TYA 

function ins_ld(op, name, reg, mode)  // 6502 load. reg is reg_a, reg_x or reg_y  
{
	opcode(op, name, mode);
	if ((mode == imm) && ((reg == reg_x) || (reg == reg_y))) {
		ins6(irq_to_f, to_t, ld, acc_a, pc_pp, nop); // get imm to T

		ins6(nop, to_mem, ld, acc_t, reg_z, upd_nz);   // 20-6-2023 store z, 15-10-2023 upd_nz
		
		final(irq_to_f, to_mem, ld, acc_t, reg, nop);   // 1-12-2023 from T to reg_x or reg_y	1-12 upd_f	 16-4-2024 remove upd_f
		print_cycles();
		return;
	}
	if ((mode == imm) && (reg == reg_a))  // new section 30-11
	{
		ins6(irq_to_f, to_a, ld, acc_a, pc_pp, upd_nz);   // 6502 loads update NZ, 20-7 irq_to_f		  
		
		final(irq_to_f, to_mem, ld, acc_a, reg_z, nop);   // 20-6-2023 store z  1-12 upd_f remove upd_f 16-4-2024		  
		print_cycles();
		return;
	}
	addr = addrmode(mode);
	if (reg == reg_a) {
		// 30-11
		if ((addr == reg_x) || (addr == reg_y)) {
			ins6(irq_to_f, to_a, ld, acc_a, addr, upd_nz);   // 6502 loads update NZ, 20-7 irq_to_f
		}
		ins6(nop, to_a, ld, acc_a, addr, upd_nz);   // 6502 loads update NZ, 20-7 irq_to_f
		// 30-11 end
		
		final(irq_to_f, to_mem, ld, acc_a, reg_z, nop);   // 20-6-2023 store z 1-12 upd_f	16-4-2024 remove upd_f
	}
	else {
		ins6(nop, to_t, ld, acc_a, addr, upd_nz);   // 6502 loads update NZ
		
		ins6(nop, to_mem, ld, acc_t, reg_z, nop);   // 30-11  20-6-2023 store z, 20-7 irq_to_f
		
		final(irq_to_f, to_mem, ld, acc_t, reg, nop); // 16-4 remove upd_f
	} 
	print_cycles();
}

// TAX TAY

function ins_taxy(op, name, reg, mode, upd)	// might update flags
// reg is reg_a, reg_x or reg_y
{
	opcode(op, name, mode);
	addr = addrmode(mode);
	//if (reg==reg_a)  // always the case
	{ 
		if (upd == upd_nz) ins6(irq_to_f, to_mem, ld, acc_a, reg_z, upd_nz); // 30-11,  new 15-10-2023
		
		final(irq_to_f, to_mem, ld, acc_a, addr, nop);  // 20-7 irq_to_f  // 30-11, 15-10-2023 moved upd 1-12 upd_f	16-4 no upd_f
	}
	print_cycles();
}

// STA STX STY

function ins_stf(op, name, reg, mode, upd)	// 6502 store, might update flags (for some transfer instructions).
// reg is reg_a, reg_x or reg_y
{
	opcode(op, name, mode);
	addr = addrmode(mode);
	if (reg == reg_a) {
		if (upd == upd_nz) ins6(nop, to_mem, ld, acc_a, reg_z, upd_nz); // new 15-10-2023
		
		final(irq_to_f, to_mem, ld, acc_a, addr, nop);  // 20-7 irq_to_f  // 30-11, 15-10-2023 moved upd 1-12 upd_f		16-4
	}
	else {
		ins6(nop, to_t, ld, acc_a, reg, upd);

		if (upd == upd_nz) ins6(nop, to_mem, ld, acc_t, reg_z, nop);   // 20-6-2023 store z  	
	
		final(irq_to_f, to_mem, ld, acc_t, addr, nop);  // 16-4
	} 
	print_cycles();
}

function ins_st(op, name, reg, mode) { ins_stf(op, name, reg, mode, nop); } // store without setting flags.




// CMP CPX CPY

function ins_cmp(op, name, reg, mode) // 6502 compare. reg is reg_a, reg_x or reg_y
{
	opcode(op, name, mode);
	// 1-12 addr = addrmode(mode);
	if (reg == reg_a) {
		addr = addrmode(mode);
		if (mode == imm) // 1-12
		{	f_is_irq = 0;
		}
		ins6(nop, to_t, sub, acc_a, addr, upd_nzc);   // result to t, unused 		
		final(irq_to_f, to_mem, ld, acc_t, reg_z, nop);   // 20-6-2023 store z, 20-7 irq_to_f 1-12 upd_f	16-4
	}
	else if (mode == imm) // new 1-12
	{
		ins6(irq_to_f, to_t, ld, acc_a, reg, nop);    	// x or y to T  21-7 irq
		addr = addrmode(mode);
		ins6(nop, to_t, sub, acc_t, addr, upd_nzc);   	// result to t, unused 		
		final(irq_to_f, to_mem, ld, acc_t, reg_z, nop);   // 20-6-2023 store z, 20-7 irq  1-12 upd_f  16-4
	}
	else {
		addr = addrmode(mode);
		ins6(nop, to_t, ld, acc_a, reg, nop);    	// x or y to T  21-7 irq
		ins6(nop, to_t, sub, acc_t, addr, upd_nzc);   	// result to t, unused 		
		final(irq_to_f, to_mem, ld, acc_t, reg_z, nop);   // 20-6-2023 store z, 20-7 irq  1-12 upd_f  16-4
	}
	print_cycles();
}

// TSX TXS

function ins_tr(op, name, from, to, upd) // register-to-register (non-accumulator).
{
	opcode(op, name, nop);
	ins6(irq_to_f, to_t, ld, acc_a, from, upd);  	// 'from' to T  20-7 irq
	if (upd == upd_nz) ins6(nop, to_mem, ld, acc_t, reg_z, nop);   // 20-6-2023 store z		
	final(irq_to_f, to_mem, ld, acc_t, to, nop);	// 30-11 T to 'to'  20-7 irq  1-12 upd_f	16-4
	print_cycles();
}

// INC DEC ASL LSR ROL ROR INX INY DEX DEY

function ins_rmw(op, name, operation, mode, upd) // read-modify-write for inc/dec/shifts
{
	opcode(op, name, mode);

	// new 15-6-2023 right-shift now uses table instead of hardware	  
	if ((operation == ror) || (operation == lsr)) {
		if ((mode == reg_a) && (operation == lsr)) {
			ins6(irq_to_f, to_dpl, xor, acc_a, lit0, nop);	// move A to dpl.	20-7 xor, irq																  
			ins6(nop, to_a, shr, acc_a, dir, upd);	// get shifted value from table (connect A0 to cy)
			
			final(irq_to_f, to_mem, ld, acc_a, reg_z, nop);  // 20-6 store z, 20-7 irq 1-12 upd_f	16-4
		}
		else if ((mode == reg_a) && (operation == ror)) {
			ins6(c_to_f, to_dpl, xor, acc_a, lit0, nop);	// move A to dpl. Cy to F (added 17-7)			  		 				
			ins6(nop, to_a, shr, acc_a, dir, upd);	// get shifted value from table. 1-12 upd_f		16-4 no upd_f
			
			if_f_t(in_f(irq_to_f, to_t, ld, acc_t, lit0, nop), in_t(irq_to_f, to_a, xor, acc_a, reg_128, upd_nz)); // 20-7 put cy in bit 7

			f_is_irq = 1;			
			final(irq_to_f, to_mem, ld, acc_a, reg_z, nop);  // 20-6 store z, 20-7 add irq_to_f  1-12 upd_f  16-4
		}
		else // when shifting at a memory location (not at reg_a)
		{
			addr = addrmode(mode); // addr can only be dir(zpage) or ext(abs)
		
			ins6(nop, to_t, ld, acc_t, dpl, nop);		// 9-11-2023 save dpl to temp. (Can not use dph)
			
			ins6(nop, to_mem, ld, acc_t, reg_tl, nop);	// 30-11 update f in next line !  16-4
			// instead of saving dpl to temp, we could also re-fetch dpl from the instruction 
			// stream when it is a zpage address. first time use (pc), second time (pc++). todo.
			// can be done for zp, zpx modes but not for abs, absx

			ins6(c_to_f, to_dpl, ld, acc_t, addr, nop);  // get data to be shifted, zpage or abs			 
			ins6(nop, to_t, shr, acc_t, dir, upd);  // get shifted data from table

			if (operation == ror)  // 1-12 put cy in bit7
				if_f_t(in_f(nop, to_dpl, ld, acc_t, lit0, nop), in_t(nop, to_t, or, acc_t, reg_128, upd_nz)); // 1-12 delay changed to nop

			ins6(nop, to_mem, ld, acc_t, reg_z, nop);  // 20-6 store z, 20-7 add irq_to_f   16-4

			ins6(irq_to_f, to_dpl, ld, acc_t, reg_tl, nop); // 9-11-2023 restore dpl from temp
			
			final(irq_to_f, to_mem, ld, acc_t, addr, nop);  // save shifted data, 20-7 irq 1-12 upd_f   16-4
		}
		print_cycles();
		return;
	}
	// end new  

	if (mode == reg_a) {
		ins6(irq_to_f, to_dpl, xor, acc_a, lit0, nop);	// move A to dpl. Have to xor-0 to move it. 20-7 irq
		if ((upd == upd_nz) || (upd == upd_nzc)) {
			ins6(nop, to_a, operation, acc_a, dpl, upd);   // operation on dpl result to A
		
			final(irq_to_f, to_mem, ld, acc_a, reg_z, nop);  // 20-6 store z, 20-7 irq  1-12 upd_f  16-4
		}
		else {
			final(nop, to_a, operation, acc_a, dpl, upd);   // operation on dpl result to A. upd will be nop.	 
			error_msg("RMW ACC without flag write shouldnt exist"); // 1-12
		}
	}
	else {
		addr = addrmode(mode);
		// 30-11
		if ((addr == reg_x) || (addr == reg_y)) {
			f_is_irq = 0;
		}
		ins6(nop, to_t, operation, acc_a, addr, upd);   // 6502 loads update NZ, 20-7 irq_to_f		16-4
		// 30-11 end
		
		if ((upd == upd_nz) || (upd == upd_nzc)) ins6(irq_to_f, to_mem, ld, acc_t, reg_z, nop);  // 20-6 store z
		
		final(irq_to_f, to_mem, ld, acc_t, addr, nop); // 16-4
	} 	
	print_cycles();
}

// ADC SBC AND ORA EOR

function ins_main(op, name, operation, mode, upd) // main code for adc/sbc/and/ora/eor 6502
{
	opcode(op, name, mode);
	if (mode == reg_a) { error_msg("invalid addr mode"); }

	else if ((operation == adc) || (operation == sbc)) {
		if (mode == imm) {
			{	f_is_irq = 0;
			}			
			ins6(nop, to_a, operation, acc_a, pc_pp, upd); // 16-4
		} // 30-11 added upd_f
		else {
			addr = addrmode(mode);
			{	f_is_irq = 0;
			}			
			ins6(nop, to_a, operation, acc_a, addr, upd); // do operation, 30-11 added upd_f   16-4
		}
		ins6(irq_to_f, to_mem, inp, acc_t, reg_v, nop);	// write V flags with 'input' instruction, 23-7 irq
		
		final(irq_to_f, to_mem, ld, acc_a, reg_z, nop); // 	1-12 upd_f  16-4

	}
	else {
		if (mode == imm) {
			f_is_irq = 0;
			ins6(nop, to_a, operation, acc_a, pc_pp, upd);
		}
		else {
			addr = addrmode(mode);
			ins6(nop, to_a, operation, acc_a, addr, upd);  	// do operation // 1-12-2023 upd_f
		}		
		final(irq_to_f, to_mem, ld, acc_a, reg_z, nop); //  1-12-2023   16-4
	}

	print_cycles();
}

// BCC BCS BEQ BNE BMI BPL BVC BVS
// 19-6 use again
function ins_vcalc(op, name, val) {
	opcode(op, name, nop);
	// jp to final instruction (BFC/BFS), opcode of final instruction in dph.
	// if val=true, set F. Else, clear F
	// The flag setting can not be in the delay instruction.
	if (val) {
		ins6(h_to_f, to_t, ld_ir, acc_t, dpl, page_6502);  // F <- 1 and load IR
	}
	else ins6(l_to_f, to_t, ld_ir, acc_t, dpl, page_6502);  // F <- 0 and load IR

	ins6(nop, to_t, ld, acc_t, reg_128, nop); // 20-7 nop in delay
	no_f_is_irq_error = 1; // allow that F is not IRQ
	no_print_cycles_upd_f_error = 1; // 1-12
	print_cycles();
}

// the following conditional branch code is for 6502 as well as for Z80 relative jumps and DJNZ

function ins_brcond(op, name, flag, polarity)  // Conditional branch. flag is c_to_f, n_to_f, z_to_f or flag_v
{
	opcode(op, name, nop);

	if (flag == flag_v)  // special action for testing overflow flag,
	{  /* 
		   JP to one of the instructions 0x02, 0x03, 0x12, 0x13, 0x22, 0x23, 0x32, 0x33
		   One of the eight instructions is chosen by 3 bits from the ALU: N, A7, B7
		   Two of these instructions will deliver V=1 (in flag F), the
		   others deliver V=0 (in flag F).
		   After one of these eight instructions, a final BFS (0x14) or BFC (0x04) will
		   be done that does the actual branch.
		   */		
		f_is_irq = 0; // 1-12 allow loading fake value in F

		ins6(nop, to_t, asl, acc_t, lit16, nop);		// get bit5 (32)
		ins6(nop, to_t, add_1, acc_t, lit16, nop);	// add bit5 and 1 to get 00110001 mask
		ins6(nop, to_t, and, acc_t, reg_v, nop);    // AND with reg_v		 
		ins6(nop, to_dpl, add_1, acc_t, lit1, nop);	 // ADD 2 and move to dpl new 26-6

		ins6(nop, to_t, ld_ir, acc_t, dpl, page_6502);	 // load Instruction register with dpl instruction
		if (polarity == true)		
		     { ins6(nop, to_dpl, ld, acc_t, lit20, nop); } // 1-12 upd_f, 0x14 BFS  16-4 remove upd_f
		else { ins6(nop, to_dpl, ld, acc_t, lit4, nop); } // 1-12 upd_f, 0x04 BFC   16-4 remove upd_f

		no_f_is_irq_error = 1; // 1-12 allow that F is not IRQ

		dis_data_bytes[(current_page << 8) + current_opcode]++; // nr of bytes in instruction
		print_cycles(); // cycles of BNS/BNC must be added to this
		return;
	}

	if (flag == nop)  // used in BFS/BFC, F flag is already set
	{	f_is_irq = 0; // 1-12 ignore the upd_f that
		// is set at the beginning of 'normal' instructions
	}

	if (name == 'DJNZ')  // here 10-11-2023
	{
		// 15-6-2024 replaced the above instructions: (it didnt work !)
		// 29-6-2024 it should work if INRZ is improved
		ins6_chi(nop, to_t, dec, acc_t, reg_b, nop);      // dec reg_b, result in T   AND CHECK INTERRUPT
		ins6_pcmin1(nop, to_mem, ld, acc_t, reg_b, nop); // store back into reg_b. Can not use Z flag, must stay unchanged		
				
		ins6(nop, to_t, dec, acc_t, reg_b, nop);	   // add FF to reg_b, gives cy in TC if nonzero  16-4
		polarity = true;
		flag = tc_to_f;
	}

	if (flag == z_to_f) { // 1-12 ins6(nop, to_t, dec, acc_a, reg_z, nop);  // get z register and add 0xFF to it		
		f_is_irq = 0; // 1-12 allow loading fake value in F
		
		ins6(nop, to_t, dec, acc_a, reg_z, nop);  // get z register and add 0xFF to it		16-4
		// tc is set when reg_z was non-zero
		flag = tc_to_f;
		if (polarity == true)  // toggle polarity
			polarity = false;
		else polarity = true;
	}

	ins6(flag, to_t, ld, acc_a, pc_pp, nop); // test condition (with 'flag') and get operand to t
	if (polarity == true) { // when jp should occur if flag is true:		
		if_f_t(in_f(next_m, nop, nop, nop, nop, nop), in_t(nop, to_dpl, add, acc_t, reg_128, nop)); // test sign bit, result in tc  16-4 no upd_f
		if_f_t(in_f(delay_m, nop, nop, nop, nop, nop), in_t(tc_to_f, to_dpl, ld, acc_t, lit0, nop));  // sign bit to F
	}
	else { // when jp should occur if flag is false:		
		if_f_t(in_f(nop, to_dpl, add, acc_t, reg_128, nop), in_t(next_m, nop, nop, nop, nop, nop)); // test sign bit, result in tc  16-4 no upd_f
		if_f_t(in_f(tc_to_f, to_dpl, ld, acc_t, lit0, nop), in_t(delay_m, nop, nop, nop, nop, nop)); // sign bit to F 
	}

	// 11-11-2023
	ins6(nop, to_pch, add, acc_t, pcl, nop); // 11-11 add pcl to t, result in pch, will in next instruction go to pcl

	// when the jump has not occurred, the previous instructions have
	// fetched the next opcode and that opcode is executed by now. No more actions needed here.
	// But when the jump should occur, pch/pcl must be updated.
	// The flag F is true if the jump is backwards. This flag is written 
	// by the t7_to_f operation in the previous cycle.
	// flag TC indicates if there is a carry from adding the offset to pcl.
	// If F is true, pch is decremented if TC is false (dec_tc operation)
	// If F is false,pch is incremented if TC is true  (inc_tc operation) 
	// Writing to pch means that also T is copied to pcl.

	if_f_t(in_f(nop, to_pch, inc_tc, acc_t, pcl, nop), in_t(nop, to_pch, dec_tc, acc_t, pcl, nop)); // 12-11-2023 use tc

	ins6(next_m, nop, nop, nop, nop, nop);   // get next instruction (at new pc position)
	ins6(delay_m, nop, nop, nop, nop, nop);  // unfortunately, the delay slot goes unused.
	print_cycles();
}

// PHA PLA

function ins_pha(op, name) 		// push A on stack
{
	opcode(op, name, nop);

	ins6(irq_to_f, to_dpl, ld, acc_a, reg_s, nop);  	// reg S to dpl. S points to empty position 
	ins6(nop, to_dph, inc, acc_t, lit0, nop);	// 0x01 to dph  1-12 upd_f   16-4

	ins6(irq_to_f, to_mem, ld, acc_a, ext, nop);	// store A in stack position 21-7 irq
	ins6(nop, to_t, dec, acc_a, dpl, nop);	// decrement S (dpl), with result to t

	final(irq_to_f, to_mem, ld, acc_t, reg_s, nop);	// store T back in stack register, 20-7 irq 1-12 upd_f  16-4

	print_cycles();
}
function ins_pla(op, name) 		// pull A from stack. It updates flags nz !
{
	opcode(op, name, nop);	
	f_is_irq = 0; // 1-12 allow loading fake value in F
	ins6(nop, to_dpl, inc, acc_a, reg_s, nop);  	// inc reg, result to dpl. 
	
	ins6(nop, to_dph, inc, acc_t, lit0, nop);	// 0x01 to dph  1-12 upd_f	  16-4
	ins6(irq_to_f, to_a, ld, acc_a, ext, upd_nz);	// get a from stack position
	ins6(nop, to_mem, ld, acc_a, reg_z, nop);  // 17-7 store z	
	ins6(nop, to_t, ld, acc_a, dpl, nop);	// move S(dpl) to t
	
	final(irq_to_f, to_mem, ld, acc_t, reg_s, nop);	// store T back in stack register, 20-7 irq 1-12 upd_f	 16-4
	print_cycles();
}

//         7 6 5 4 3 2 1 0
// flags:  N V - B D I Z C  // 6502
// Isetta: N V V - - Z V C  (Z is inverted)

// PHP PLP

function ins_php(op, name) 		// push P (status register) on stack
{
	opcode(op, name, nop);
	// first construct the flags byte
	// 5-7-2023 new, format NVV--ZVC
	// V state from reg_v, relevant bits: 00110001
	// Pack flags NVZC into one byte: (to T register)

	f_is_irq = 0; // 1-12 allow loading fake value in F
	ins6(nop, to_dpl, rol, acc_t, reg_v, nop);  // get V bits, shift left -VV---VC  and put cy in bit0  16-4
	ins6(n_to_f, to_t, ld, acc_t, reg_128, nop);      // bit7 in t, n flag to F

	// F: reset bit 7                        T: set bit 7
	if_f_t(in_f(nop, to_dpl, res, acc_t, dpl, nop), in_t(nop, to_dpl, or, acc_t, dpl, nop)); // reset or set bit7

	// we now have NVV---VC (in DPL)

	ins6(nop, to_dph, dec, acc_t, reg_z, nop); // Z state to TC (inverted). 1-12 upd_f  16-4

	ins6(tc_to_f, to_t, ld, acc_t, lit4, nop);      // bit2 in t, tc_flag to F

	//    F: reset bit2                        T: set bit2   // Bit2 becomes NOT-Z
	if_f_t(in_f(nop, to_t, res, acc_t, dpl, nop), in_t(nop, to_t, or, acc_t, dpl, nop)); // set or reset bit2

	// final result NVV--ZVC  (Z is inverted)

	// now put it on stack
	ins6(nop, to_dpl, ld, acc_a, reg_s, nop);  	// reg S to dpl. S points to empty position 
	
	ins6(nop, to_dph, inc, acc_t, lit0, nop);	// 0x01 to dph 1-12 upd_f	16-4
	ins6(irq_to_f, to_mem, ld, acc_t, ext, nop);	// store T at stack position 21-7 irq
	ins6(nop, to_t, dec, acc_a, dpl, nop);	// decrement S (dpl), with result to t
	
	final(irq_to_f, to_mem, ld, acc_t, reg_s, nop);	// store T back in stack register, 20-7 irq 1-12 upd_f	16-4
	print_cycles();
}

//         7 6 5 4 3 2 1 0
// flags:  N V - B D I Z C  // 6502
// Isetta: N V V - - Z V C  (Z is inverted)

function ins_plp(op, name) 		// pull P from stack.
{
	opcode(op, name, nop);

	f_is_irq = 0; // 1-12 allow loading fake value in F

	ins6(nop, to_dpl, inc, acc_a, reg_s, nop);  	// inc reg, result to dpl. 
	ins6(nop, to_dph, inc, acc_t, lit0, nop);	// 0x01 to dph
	ins6(nop, to_t, ld, acc_a, dpl, nop);	// move S(dpl) to t
	ins6(nop, to_mem, ld, acc_t, reg_s, nop);	// store T back in stack register

	// get the bits from P and put them in flags again
	// 5-7-2023 storage format:  NVV--ZVC  (Z is inverted)
	ins6(nop, to_t, ld, acc_t, ext, upd_n);    // get flags, update N flag
	ins6(nop, to_t, and, acc_t, lit4, nop); // AND with value 0x04  00000100 to get NOT-Z
	
	ins6(nop, to_mem, ld, acc_t, reg_z, nop);  // store the z condition in register_z 1-12 upd_f	 16-4

	ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop);    // get flags to dpl
	ins6(nop, to_t, shr, acc_t, dir, upd_c); // do a right shift, obtain C and have V in position			   

	final(irq_to_f, to_mem, ld, acc_t, reg_v, nop);  // store the three v flags, 20-7 irq 1-12 upd_f	16-4
	print_cycles();
}

function ins_nop(op, name) 		// a NOP or non-implemented instruction. 6502 and Z80.
{
	opcode(op, name, nop);

	final(irq_to_f, to_t, ld, acc_a, lit0, nop);  // 14-4-2024 check interrupt !
	print_cycles();
}

function ins_clc(op, name) 		// clear carry  CLC 
{
	opcode(op, name, nop);
	
	f_is_irq = 0; // 1-12 allow loading fake value in F
	// 15-10-2023  update C or N must not be last cycle
	ins6(next_m, nop, nop, nop, nop, clr_c);	 // 12-11-2023
	ins6(delay_m, nop, nop, nop, nop, nop);
	print_cycles();
}
function ins_sec(op, name) 		// set carry  SEC
{
	opcode(op, name, nop);
	
	f_is_irq = 0; // 1-12 allow loading fake value in F
	// 15-10-2023  update C or N must not be last cycle
	ins6(next_m, nop, nop, nop, nop, set_c);	 // 12-11-2023
	ins6(delay_m, nop, nop, nop, nop, nop);
	print_cycles();
}

function ins_clv(op, name) 		// clear overflow  CLV
{
	opcode(op, name, nop);
	ins6(irq_to_f, to_t, ld, acc_t, lit0, nop);  // set T to 0, 5-7-2023  21-7 irq
	
	final(irq_to_f, to_mem, ld, acc_t, reg_v, nop);   	// store in reg_v, 20-7 irq 1-12 upd_f	16-4
	print_cycles();
}

function ins_int6502(op, name) 		// interrupt (at 0x80). 
{
	opcode(op, name, nop);
	
	f_is_irq = 0; // 1-12 allow loading fake value in F

	ins6(nop, to_t, ld, acc_t, lit0, nop);	 // clear T	
	f_is_irq = 0; // prevent that INTERRUPT will interrupt itself 
	
	ins6(irq_to_f, to_t, ld_ir, acc_t, reg_kb_state, page_reset);  // 10-4-2024 jp to KB device handler 
	ins6(delay_m, nop, nop, nop, nop, nop);
	no_print_cycles_upd_f_error = 1; // 1-12	  
	print_cycles();
} 

function ins_inr6(op, name) 		// interrupt (at 0x05). No function yet
{
	opcode_page(page_reset, op, name, nop, nop);   // this one is in the reset page
	did_f_upd_f = 0; did_t_upd_f = 0; f_is_irq = 0; // 1-12 allow loading fake value in F

	ins6(nop, to_t, ld, acc_t, lit0, nop);	 // clear T	
	f_is_irq = 0; // prevent that INTERRUPT will interrupt itself 
	final(irq_to_f, to_dpl, ld, acc_t, lit0, nop);   	// clr dpl, irq_to_f
	// TODO:  PC = PC - 2;
	no_print_cycles_upd_f_error = 1; // 1-12
	print_cycles();
}

function ins_bit(op, name, mode) 		// 6502 BIT instruction
{
	opcode(op, name, mode);
	addr = addrmode(mode);
	// 26-10-2023 previous one tested Z while the address was corrupted, because used for shifting.
	// handle flag Z:
	
	ins6(nop, to_t, sub, acc_a, addr, upd_z);		// compare A with operand, update Z flag 1-12 upd_f	 16-4
	ins6(irq_to_f, to_mem, ld, acc_t, reg_z, nop);  // store z	, 21-7 irq	  
	// handle flag N:
	ins6(nop, to_t, ld, acc_a, addr, upd_n);  		// load operand, bit7 to N flag
	// handle flag V:
	ins6(nop, to_dpl, asl, acc_a, addr, nop);		// operand shift-left, bit6(V) is now at bit7 position
	ins6(nop, to_dpl, asl, acc_a, dpl, nop);	  	// shift-left, V flag in TC
	ins6(nop, to_t, inc_tc, acc_a, lit0, nop);		// put TC in bit0 of a zero-byte
	// writing to v can be done after LD_IR because it doesnt use INPUT instruction	
	final(irq_to_f, to_mem, ld, acc_t, reg_v, nop);		// write v flag to reg_v: --00---V 1-12 upd_f	16-4
	print_cycles();
}

function ins_jmp(op, name, mode) 		// JMP  jump
{
	opcode(op, name, mode);
	if (mode == abs) {
		ins6(irq_to_f, to_t, ld, acc_a, pc_pp, nop); // get low addr to t			 
		ins6(nop, to_dpl, ld, acc_t, pc_pp, nop);	// 12-11 dpl <- (pc++)
		ins6(nop, to_pch, xor, acc_t, lit0, nop);  // 12-11 lsb, pch <- t
		ins6(nop, to_pch, ld, acc_t, dpl, nop);    // 12-11 msb, pch <- dpl 
	}
	else if (mode == ind) {
		ins6(irq_to_f, to_dpl, ld, acc_a, pc_pp, nop); // get low addr to dpl 1-12 irq_to_f
		ins6(nop, to_dph, ld, acc_t, pc_pp, nop); // get high addr to dph // 29-10-2024 change acc_a to acc_t
		// now do the indirection step		
		ins6(nop, to_pch, ld, acc_a, ext, nop); 	// 12-11 get low addr to pch		
		ins6(nop, to_dpl, inc, acc_t, dpl, nop);		// dpl increment 1-12 upd_f		16-4
		// carry to dph ? No ! Famous 6502 'bug'.		  
		ins6(irq_to_f, to_pch, ld, acc_t, ext, nop);	// move to pch and also pch to pcl 21-7 irq
	}
	else { error_msg("unknown addressing mode"); }
	final(delay_m, nop, nop, nop, nop, nop);
	print_cycles();
}


// 13-11-2023 new JSR  (derived from Z80)
function ins_jsr(op, name, mode) 		// CALL   subroutine.
{
	opcode(op, name, abs);

	ins6(irq_to_f, to_dpl, ld, acc_a, pc_pp, nop); // 13-11 get low dst addr to dpl, inc pc 1-12 irq_to_f

	ins6(nop, to_t, ld, acc_a, pc_ind, nop); 	// get high dst addr to T, (NOT inc pc)

	ins6(nop, to_t, ld_ir, acc_t, lit8, page_reset); // jump to RCAL (routine-call 6502)
	ins6(nop, to_mem, ld, acc_t, reg_th, nop); 		// save in temp reg_th

	no_f_is_irq_error = 1; // suppress error
	no_print_cycles_upd_f_error = 1; // 1-12
	print_cycles();
}


// 8-11-2023 new function. Code for CALL is too long, it is continued here as RCAL (routine-call)
function ins_rcal(page, opc, name) {
	opcode_page(page, opc, name, nop, nop); 	// instruction 08 in reset group (page 0)
	// 16-4 co: did_f_upd_f = 0; did_t_upd_f = 0; 
	f_is_irq = 0; // 1-12 allow loading fake value in F

	ins6(nop, to_t, ld, acc_t, pcl, nop);		// 13-11 get pcl move it to t, no dtc_to_f
	ins6(nop, to_pch, ld, acc_t, dpl, nop); // 13-11 pcl<-pch, pch<-target_low (from dpl)
	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // store pcl (re-use reg_tl)
	ins6(nop, to_t, ld, acc_t, pcl, nop); // t <- pcl (this is actuall pc-msb)

	ins6(nop, to_dpl, ld, acc_a, reg_s, nop);   // 13-11 load s. not decr here !

	ins6(nop, to_dph, ld, acc_t, lit1, nop); // load sph(1)  1-12 upd_f	 16-4
	ins6(dtc_to_f, to_mem, ld, acc_t, ext, nop);	// 13-11 store pc-msb to stack

	// F=0 crossed page       F=1 not crossed page
	
	ins6(nop, to_dpl, dec, acc_t, dpl, nop);   // dec dpl  1-12 upd_f	16-4
	ins6(tc_to_f, to_t, ld, acc_t, reg_tl, nop);  // if true, pcl to T, tc_to_f

	// F=0 crossed page       F=1 not crossed page
	
	ins6(nop, to_mem, ld, acc_t, ext, nop);  // if true, save T (LSB) to stack  4-12 upd_f	16-4
	ins6(irq_to_f, to_pch, ld, acc_t, reg_th, nop);  // if true, load pch & pcl 4-12 irq_to_f

	ins6(nop, to_t, dec, acc_t, dpl, nop);  // 13-11 if true, dpl to T, decrementing
	
	final(irq_to_f, to_mem, ld, acc_t, reg_s, nop);   // if true,store T to stackpt 1-12 upd_f	
	print_cycles();
}


function ins_rts(op, name) 		// RTS  return from subroutine
{
	opcode(op, name, nop);

	f_is_irq = 0; // 1-12 allow loading fake value in F

	ins6(nop, to_dpl, inc, acc_a, reg_s, nop);// reg S to dpl, incremented. (S did point to empty position )
	ins6(nop, to_dph, inc, acc_t, lit0, nop);	// 0x01 to dph 
	ins6(nop, to_pch, inc, acc_t, ext, nop);	// 12-11 get low byte in pch, increment it
	ins6(nop, to_dpl, inc, acc_a, dpl, nop);	// increment S (dpl)
	ins6(nop, to_pch, inc_dtc, acc_t, ext, nop);		// move to pch (increment if needed) and also pch to pcl 1-12 upd_f 16-4
	ins6(irq_to_f, to_t, ld, acc_a, dpl, nop);  	//  dpl to T  
	
	final(irq_to_f, to_mem, ld, acc_t, reg_s, nop); 	// at the end, store S back in register, 20-7 irq 1-12 upd_f 16-4
	print_cycles();
}


function ins_in(op, name) 		// INPUT instruction, 6502 and all other processors
{
	opcode(op, name, nop);
	
	ins6_chi(nop, to_t, ld_ir, acc_t, pc_pp, page_in); // jump to the specific input instruction
	ins6_pcmin1(delay_m, nop, nop, nop, nop, nop);
   
	print_cycles();
}


function ins_out(op, name) 		// OUTPUT instruction, 6502 and all other processors
{
	opcode(op, name, nop);

	ins6_chi(nop, to_t, ld_ir, acc_t, pc_pp, page_out); // jump to the specific output instruction
	ins6_pcmin1(delay_m, nop, nop, nop, nop, nop);	
	print_cycles();
}


function ins_in_ind(opc,name,dst,src)	// new 7-6-2024
  { opcode_page(page_z80_ed, opc, name, dst, src);   // in a,(c)   Z80 only
  
	ins6(irq_to_f, to_t, ld_ir, acc_t, reg_c, page_in); // jump to the specific input instruction
	ins6(delay_m, nop, nop, nop, nop, nop);
	
    print_cycles();
  }

// 4-11-2024 The out (c),reg  has special meaning for Amstrad CPC. It does bankswitching.
// Isetta also does that.
// if reg_os==0  -> normal output function
// if reg_os == 0x40 and src==0x11xxxxxx --> bankswitching
// if reg_os !=0 and src!=0x11xxxxxx --> do nothing (Amstrad CPC writes other registers in this case)
// The normal function works for the moment only for reg A, because that's what normal I/O uses (TODO).

function ins_out_ind(opc,name,dst,src)	// new 7-6-2024
  { opcode_page(page_z80_ed, opc, name, dst, src);   // out (c),a   Z80 only
 
	// 30-11-2024 put this instruction out of order
	// 21-12-2024 enable again (outcommenting the final)

	// 4-11-2024
	ins6(nop, to_t, dec, acc_a, reg_os, nop); // if reg_os indicates OS, set tc

	if (src == reg_a)
	   ins6(tc_to_f, to_t, xor, acc_a, lit0, nop); // acc_a to T
	else   
	   ins6(tc_to_f, to_t, ld, acc_t, src, nop);  // src register to T (when src!=acc_a)

	//  F=0  No OS (reg_os==0), normal output.     F=1  OS active, this is a bankswitch command. save src in reg_tl
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, reg_c, page_out), in_t(nop, to_dpl, add, acc_t, reg_os, nop)); // add 0x40 (if OS) or add 0x00
 	if_f_t(in_f(delay_m, nop, nop, nop, nop, nop),in_t(tc_to_f, to_mem, ld, acc_t, reg_tl, nop)); // save T in reg_tl, if src = 11xxxxxx AND OS=0x40, then set F flag

	/* 28-11-2025 removed
	ins6(nop, to_t, asl, acc_t, lit32, nop);  // 13-11-2025  T <- bit6
	ins6(nop, to_t, res, acc_t, reg_tl, nop); // 13-11-2025  T <- reg_tl (reset bit6). Address only low 512k section.
	ins6(h_to_f, to_mem, ld, acc_t, reg_tl, nop) ; // 13-11-2025 back to reg. 6.  Set F.

	//  F=0  OS, but not 11xxxxxx. next instr.     F=1  this is a 11xxxxx bankswitch command. save src in reg_tl
	if_f_t(in_f(next_m,nop,nop,nop,nop,nop), in_t(nop, to_t, dec, acc_t, lit8, nop)); // T <- 7
 	if_f_t(in_f(delay_m, nop, nop, nop, nop, nop),in_t(nop, to_dpl, and, acc_t, reg_tl, nop)); //  T <- src & 0x07

	// continue if it is a bankswitch command

	ins6(nop,to_dph,ld,acc_t,lit1,nop);  // 24-6-2025 for SHR in bc0-bc7
 
    // now jump to one of 8 destinations, based on contents of T, going to 0-7 in page_out
    
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_out); // jp to BC0 - BC7 in page_out
 	ins6(delay_m, nop, nop, nop, nop, nop);	
	*/
	// 28-11-2025 make a jmp to port_out_sbnk

	make_literal(to_t, port_out_sbnk);
	ins6(nop, to_dpl, xor, acc_t, lit0, nop); //  DPL <- T

    // now jump to port_out_sbnk
    
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_out); 
 	ins6(delay_m, nop, nop, nop, nop, nop);	

    print_cycles();
  }

/* 18-11-2025 changed
function ins_out_sbnk(opc,name,dst,src)	// new 18-3-2025  set SymbOs bank number
  { opcode_page(page_out, opc, name, dst, src);   // out (port_out_sbnk),a   Z80 only
  
	// bankswitch command 

	ins6(nop, to_dpl, or, acc_a, lit0, nop); // acc to dpl
	ins6(nop, to_t, asl, acc_t, lit32, nop); // get BIT6
	// 13-11-2025 ins6(nop, to_t, or, acc_t, dpl, nop); //  T <- dpl OR bit6
	ins6(nop, to_t, res, acc_t, dpl, nop); //  T <- dpl with bit6 reset  13-11-2025

	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // save T in reg_tl

	ins6(nop, to_t, dec, acc_t, lit8, nop);     // T <- 7
	ins6(nop, to_dpl, and, acc_t, reg_tl, nop); //  T <- src & 0x07
 
	ins6(nop,to_dph,ld,acc_t,lit1,nop);  // 24-6-2025 for SHR in bc0-bc7
    // now jump to one of 8 destinations, based on contents of T, going to 0-7 in page_out
    
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_out); // jp to BC0 - BC7 in page_out
 	ins6(delay_m, nop, nop, nop, nop, nop);	
    print_cycles();
  }
*/

// 18-11-2025 now also do the shifting here.
function ins_out_sbnk(opc,name,dst,src)	// new 18-11-2025  set SymbOs bank number
  { opcode_page(page_out, opc, name, dst, src);   // out (port_out_sbnk),a   Z80 only  A = C0, C1, C2, C4-7
  
	// bankswitch command 
	ins6(nop,to_dph,ld,acc_t,lit1,nop);  // 24-6-2025 for SHR
	ins6(nop, to_dpl, or, acc_a, lit0, nop); // acc to dpl
	ins6(nop, to_dpl, shrnew, acc_t, ext, nop); // shift
	ins6(nop, to_dpl, shrnew, acc_t, ext, nop); // shift
	ins6(nop, to_t,   shrnew, acc_t, ext, nop); // shift 3x, now ---1 NBBB

	ins6(nop, to_t, xor, acc_t,lit8,nop) // invert bit3 (1 -> A19 low, 0 -> A19 high)
	
	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // save T in reg_tl

	ins6(nop, to_dpl, or, acc_a, lit0, nop); // acc to dpl again
	ins6(nop, to_t, dec, acc_t, lit8, nop);     // T <- 7
	ins6(nop, to_dpl, and, acc_t, dpl, nop); //  DPL <- src & 0x07

    // now jump to one of 8 destinations, based on contents of T, going to 0-7 in page_out
    
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_out); // jp to BC0 - BC7 in page_out
 	ins6(delay_m, nop, nop, nop, nop, nop);	
    print_cycles();
  }

// 25-11-2025 combination of bankswitch and jump, D3 1E 34 12 switches bank and jumps to #1234
function ins_out_sbnkjp(opc,name,dst,src)	//   set SymbOs bank number
  { opcode_page(page_out, opc, name, dst, src);   // out (port_out_sbnkjp),a  (must be followed by JP address)
  
	// jump
	ins6(irq_to_f, to_t, ld, acc_a, pc_pp, nop); // get low addr to t			 
	ins6(nop, to_dpl, ld, acc_t, pc_pp, nop);	// 12-11 dpl <- (pc++)
	ins6(nop, to_pch, xor, acc_t, lit0, nop);  // 12-11 lsb, pch <- t
	ins6(nop, to_pch, ld, acc_t, dpl, nop);    // 12-11 msb, pch <- dpl 

	// bankswitch command 
	ins6(nop,to_dph,ld,acc_t,lit1,nop);  // 24-6-2025 for SHR
	ins6(nop, to_dpl, or, acc_a, lit0, nop); // acc to dpl
	ins6(nop, to_dpl, shrnew, acc_t, ext, nop); // shift
	ins6(nop, to_dpl, shrnew, acc_t, ext, nop); // shift
	ins6(nop, to_t,   shrnew, acc_t, ext, nop); // shift 3x, now ---1 NBBB

	ins6(nop, to_t, xor, acc_t,lit8,nop) // invert bit3 (1 -> A19 low, 0 -> A19 high)
	
	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // save T in reg_tl

	ins6(nop, to_dpl, or, acc_a, lit0, nop); // acc to dpl again
	ins6(nop, to_t, dec, acc_t, lit8, nop);     // T <- 7
	ins6(nop, to_dpl, and, acc_t, dpl, nop); //  T <- src & 0x07

    // now jump to one of 8 destinations, based on contents of T, going to 0-7 in page_out
    
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_out); // jp to BC0 - BC7 in page_out
 	ins6(delay_m, nop, nop, nop, nop, nop);	
    print_cycles();
  }


function ins_out_wbnk(opc,name,dst,src)	// new 26-11-2025  set SymbOs bank number   Z80 only
  { opcode_page(page_out, opc, name, dst, src);   // out (port_out_sbnk),a   Z80 only  A = Symbos banknr 0-15
  
	ins6(nop,to_t,asl,acc_t,lit32,nop); // T <- bit6
	ins6(nop,to_t,or,acc_t,reg_128,nop);    // T = 11000000
	ins6(nop,to_dpl,and,acc_t,reg_h,nop);  // DPL <- T and reg_h  // use the two top bits of reg H

	ins6(nop,to_t,and_tst,acc_a,lit8,nop);  //  A and_tst bit3
	ins6(tc_to_f,to_dph,ld,acc_t,lit1,nop);  //  DPH <- 1. tc_to_f

	ins6(nop,to_t,and,acc_a,reg_0F,nop);  //  T <- A and 0x0F

	// F=0  (lower 512k)   F=1: upper 512k
	if_f_t(in_f(nop, to_t, add_1, acc_t, lit1, nop), in_t(nop, to_t, xor, acc_t, lit0, nop)); // F0: T <- T + 2   F1: nop
	if_f_t(in_f(nop, to_t, add, acc_t, lit1, nop), in_t(nop, to_t, xor, acc_t, lit0, nop)); // F0: T <- T + 1   F1: nop
	if_f_t(in_f(nop, to_t, res2, acc_t, lit8, nop), in_t(irq_to_f, to_t, xor, acc_t, lit0, nop));// F0: reset bit3 in T  F1: nop

	ins6(nop, to_dpl, shrnew, acc_t, ext, nop); // shift
	ins6(nop, to_dpl, shrnew, acc_t, ext, nop); // shift, now dpl = 00xx0000

	ins6(nop,to_t,or,acc_t,dpl,nop);  //  T <- T or DPL
	ins6(nop, to_mem, ld, acc_t, reg_bank_dp, nop);	// save a copy of the bankswitch register
	ins6(nop, to_bnk, ld, acc_a, reg_bank_dp, nop); // Write BANK register. also writes dph. uses acc_a.

	ins6(nop, l_to_sw_slot3, ld, acc_t, lit0, nop);	 // set slot3 low (slot 1 is used)

	final(irq_to_f, to_t, ld, acc_a, lit0, nop); // fetch next Z80 instruction.   16 cycles

    print_cycles();
  }



// the SymbOS function BNKRBT can be done by the following sequence:
//  wbnk
//  rbt
//  inc hl

function ins_in_rbt(opc,name,dst,src)	// new 26-11-2025  RBT  read byte   Z80 only  read membank byte into B register
  { opcode_page(page_in, opc, name, dst, src);   // out (port_out_sbnk),a   Z80 only  A = Symbos banknr 0-15
  
	ins6(nop,to_t,asl,acc_t,lit32,nop); // T <- bit6
	ins6(nop,to_t,or,acc_t,reg_h,nop);    // T <- T or reg_h  
	ins6(nop,to_dph,res2,acc_t,reg_128,nop);  // DPH <- T reset bit7
	ins6(nop,to_dpl,ld,acc_t,reg_l,nop);  // DPL <- reg_l

	ins6(nop,to_t,ld,acc_t,ext,nop); //  T <- (dph|dpl)
	ins6(nop,to_mem,ld,acc_t,reg_b,nop); // reg_b <- T

	final(irq_to_f, to_t, ld, acc_a, lit0, nop); // fetch next Z80 instruction.
    print_cycles();
  }

function ins_out_wbt(opc,name,dst,src)	// new 26-11-2025  WBT  write byte   Z80 only  write C register to membank
  { opcode_page(page_out, opc, name, dst, src);   // out (port_out_sbnk),a   Z80 only  A = Symbos banknr 0-15
  
	ins6(nop,to_t,asl,acc_t,lit32,nop); // T <- bit6
	ins6(nop,to_t,or,acc_t,reg_h,nop);    // T <- T or reg_h  
	ins6(nop,to_dph,res2,acc_t,reg_128,nop);  // DPH <- T reset bit7
	ins6(nop,to_dpl,ld,acc_t,reg_l,nop);  // DPL <- reg_l

	ins6(nop,to_t,ld,acc_t,reg_c,nop); //  T <- reg_c
	ins6(nop,to_mem,ld,acc_t,ext,nop); //   (dph|dpl) <- T

	final(irq_to_f, to_t, ld, acc_a, lit0, nop); // fetch next Z80 instruction.
    print_cycles();
  }

// bankswitch. Only for Z80 operating system. According to Amstrad CPC system.
// Accepts nr 0 - 7.
// The ins_bsw can not be used on it's own. Always use out(#1B),A that will jp to one of these.
/* 13-11-2025
function ins_bsw(opc,name,nr)	// new 4-11-2024. BC0 - BC7 in page_out
  { opcode_page(page_out, opc, name, nop,nop);   // 

	// 24-6-2025 DPH is filled with 1 in the instruction that jumps here.

    if ((nr==0)  // mode C0. Kernel only. Set APPL = 1 and bank = 3, PC18=0  (HW_bank=3, OS_BANK=0)
	     || (nr==3))   // nr 3 is not used, and not possible on Isetta. Handle it as C0.
	{	ins6(nop, to_t, dec, acc_t, lit0, nop);	 // T <- FF
		ins6(nop, to_dpl, sub, acc_t, lit4, nop);  // T <- T - 4; T = 1111 1011
		// BNK register is special. 4th parameter to 'ins6' must be acc_a.
		ins6(nop, to_bnk, ld, acc_a, dpl, nop); // Write BANK register. also writes dph. uses acc_a.
		ins6(nop, to_t, ld, acc_t, dpl, nop); // 22-11-2024 bank to T
		// 9-3-2025  ins6(nop, to_mem, ld, acc_t, reg_bank_dp, nop); // 22-11-2024 save a copy of the selected bank
		ins6(irq_to_f, to_mem, ld, acc_t, reg_bank_dp, nop); // 22-11-2024 save a copy of the selected bank. 9-3 irq_to_f

		ins6(nop, l_to_sw_pc18, ld, acc_t, lit0, nop);	 // set PC18 low
		final(irq_to_f, to_t, ld, acc_a, lit0, nop); // fetch next Z80 instruction
		print_cycles();
		return;
	}
	else if (nr==1) // mode C1  APPL = 0
	{	ins6(nop, h_to_sw_slot3, ld, acc_t, lit0, nop);	 // set slot3 high	
	    appl = 0;	
		blocknr = 3;
		// now it can be handled same as C4-C7
	}
	else if (nr==2) // mode C2  
	{	// blocknr is don't care. APPL=1	    
	    appl = 1;
		blocknr = 1; // actually it's don't care. But this is slightly faster.
	}
	else  // mode C4 - C7  APPL=0
	{	ins6(nop, l_to_sw_slot3, ld, acc_t, lit0, nop);	 // set slot3 low (slot 1 is used)
        appl = 0; 
		blocknr = nr - 4; // for C4-C7 modes
	}
    // blocknr to nn, appl to A
	
	ins6(nop, to_dpl, ld, acc_t, reg_tl, nop);  // 22-12-2024 get original byte. OS bank in bit 4,5,6
	// original byte is 11bbb---
	// 24-6-2024
	ins6(nop, to_dpl, shrnew, acc_t, ext, nop); // shift right (3 times in total)

	if (appl==1) 
		{ ins6(nop, to_t, shrnew, acc_t, ext, nop);   // shift, result to T
	      ins6(nop, to_dpl, or, acc_t, reg_128, nop);	// set top bit, becomes 'A' bit	. result in dpl.
		}
	else  ins6(nop, to_dpl, shrnew, acc_t, ext, nop);   // shift, result to dpl

	ins6(nop, to_t, shrnew, acc_t, ext, nop); // shift, now have 0A011bbb	

	if (blocknr == 0 ) ins6(nop, to_t, sub, acc_t, lit16, nop);	// 0A011bbb -  10000 = 0A001bbb (nn=00)
	// for blocknr==1, it already is nn=01.
	if (blocknr == 2 ) ins6(nop, to_t, add, acc_t, lit16, nop);	// 0A011bbb +  10000 = 0A101bbb (nn=10)
	if (blocknr == 3 ) ins6(nop, to_t, or, acc_t, lit32, nop);  // 0A011bbb + 100000 = 0A111bbb (nn=11)
	ins6(nop, to_t, or, acc_t, reg_128, nop);	// set top bit, now have 1Ann1bbb

	// add 1 to bank number. and then add 3. Same as xor 4 (modulo 8)
	ins6(nop, to_t, xor, acc_t, lit4, nop);  // xor 4

	// BNK register is special. 4th parameter to 'ins6' must be acc_a.
	ins6(nop, to_dpl, add, acc_t, lit0, nop); // copy T to dpl
	ins6(nop, to_bnk, ld, acc_a, dpl, nop); // also writes dph. uses acc_a.
	// 9-3-2025 ins6(nop, to_mem, ld, acc_t, reg_bank_dp, nop); // 22-11-2024 save a copy of the selected bank
	ins6(irq_to_f, to_mem, ld, acc_t, reg_bank_dp, nop); // 22-11-2024 save a copy of the selected bank	. 9-3 irq_to_f

    // now copy highest bit of bank nr to pc18
	ins6(nop, to_dpl, and, acc_t, lit4, nop);  // dpl <- T and 4
	ins6(nop, to_t, dec, acc_t, dpl, nop);  // dec. set TC if bit was 1

    ins6(nop, tc_to_sw_pc18, ld, acc_t, lit0, nop);	 // write TC to PC18

	final(irq_to_f, to_t, ld, acc_a, lit0, nop); // fetch next Z80 instruction
    print_cycles();
  }
*/
// 13-11-2025

function ins_bsw(opc,name,nr)	// new 4-11-2024. BC0 - BC7 in page_out
  { opcode_page(page_out, opc, name, nop,nop);   // 

	// 24-6-2025 DPH is filled with 1 in the instruction that jumps here.

    if ((nr==0)  // mode C0. Kernel only. Set APPL = 1 and bank = 3, PC18=0  (HW_bank=3, OS_BANK=0)
	     || (nr==3))   // nr 3 is not used, and not possible on Isetta. Handle it as C0.
	{	ins6(nop, to_t, dec, acc_t, lit0, nop);	 // T <- FF
		ins6(nop, to_t, res2, acc_t, lit8, nop); // new 13-11-2025, reset bit 3, giving F7
		ins6(nop, to_dpl, sub, acc_t, lit4, nop);  // T <- T - 4; T = 1111 1011  (13-11-2025  1111 0011)
		// BNK register is special. 4th parameter to 'ins6' must be acc_a.
		ins6(nop, to_bnk, ld, acc_a, dpl, nop); // Write BANK register. also writes dph. uses acc_a.
		ins6(nop, to_t, ld, acc_t, dpl, nop); // 22-11-2024 bank to T
		// 9-3-2025  ins6(nop, to_mem, ld, acc_t, reg_bank_dp, nop); // 22-11-2024 save a copy of the selected bank
		ins6(irq_to_f, to_mem, ld, acc_t, reg_bank_dp, nop); // 22-11-2024 save a copy of the selected bank. 9-3 irq_to_f

		ins6(nop, l_to_sw_pc18, ld, acc_t, lit0, nop);	 // set PC18 low
		ins6(nop, l_to_sw_pc19, ld, acc_t, lit0, nop);	 // 18-11-2025  set PC19 low
		final(irq_to_f, to_t, ld, acc_a, lit0, nop); // fetch next Z80 instruction
		print_cycles();
		return;
	}
	else if (nr==1) // mode C1  APPL = 0
	{	ins6(nop, h_to_sw_slot3, ld, acc_t, lit0, nop);	 // set slot3 high	
	    appl = 0;	
		blocknr = 3;
		// now it can be handled same as C4-C7
	}
	else if (nr==2) // mode C2  
	{	// blocknr is don't care. APPL=1	    
	    appl = 1;
		blocknr = 1; // actually it's don't care. But this is slightly faster.
	}
	else  // mode C4 - C7  APPL=0
	{	ins6(nop, l_to_sw_slot3, ld, acc_t, lit0, nop);	 // set slot3 low (slot 1 is used)
        appl = 0; 
		blocknr = nr - 4; // for C4-C7 modes
	}
    // blocknr to nn, appl to A
	
	/* 18-11-2025
	ins6(nop, to_dpl, ld, acc_t, reg_tl, nop);  // 22-12-2024 get original byte.
	// original byte is 11bbb---
	// 24-6-2024
	ins6(nop, to_dpl, shrnew, acc_t, ext, nop); // shift right (3 times in total)
	if (appl==1) 
		{ ins6(nop, to_t, shrnew, acc_t, ext, nop);   // shift, result to T
	      ins6(nop, to_dpl, or, acc_t, reg_128, nop);	// set top bit, becomes 'A' bit	. result in dpl.
		}
	else  ins6(nop, to_dpl, shrnew, acc_t, ext, nop);   // shift, result to dpl
	ins6(nop, to_t, shrnew, acc_t, ext, nop); // shift, now have 0A011bbb	

	if (blocknr == 0 ) ins6(nop, to_t, sub, acc_t, lit16, nop);	// 0A011bbb -  10000 = 0A001bbb (nn=00)
	// for blocknr==1, it already is nn=01.
	if (blocknr == 2 ) ins6(nop, to_t, add, acc_t, lit16, nop);	// 0A011bbb +  10000 = 0A101bbb (nn=10)
	if (blocknr == 3 ) ins6(nop, to_t, or, acc_t, lit32, nop);  // 0A011bbb + 100000 = 0A111bbb (nn=11)
	ins6(nop, to_t, or, acc_t, reg_128, nop);	// set top bit, now have 1Ann1bbb

	// add 1 to bank number. and then add 3. Same as xor 4 (modulo 8)
	ins6(nop, to_t, xor, acc_t, lit4, nop);  // xor 4	
	*/
	// new 18-11-2025
	ins6(nop, to_t, asl, acc_t, lit32, nop); // T <- 0x40
	if (appl==1)
		ins6(nop, to_t, or, acc_t, reg_tl, nop)   // load bank nr, set appl bit
	else ins6(nop, to_t, ld, acc_t, reg_tl, nop)  // load bank nr

	if (blocknr == 0 ) ins6(nop, to_t, sub, acc_t, lit16, nop);	// 0A011bbb -  10000 = 0A00Nbbb (nn=00)
	// for blocknr==1, it already is nn=01.
	if (blocknr == 2 ) ins6(nop, to_t, add, acc_t, lit16, nop);	// 0A011bbb +  10000 = 0A10Nbbb (nn=10)
	if (blocknr == 3 ) ins6(nop, to_t, or, acc_t, lit32, nop);  // 0A011bbb + 100000 = 0A11Nbbb (nn=11)
	// 18-11-2025 end

	/* this seems the wrong vision. remove it, adjust pc19 at the end.
	ins6(nop, to_a, add, acc_t, lit1, nop); // A <- T + 1  
	ins6(nop, to_dpl, and_tst, acc_a, lit8, nop);  // dpl (dummy) <- A and 8, set TC if nonzero
	// TC=0 -> basic RAM  TC=1 -> extra 512K RAM
	ins6(tc_to_f, tc_to_sw_pc19, ld, acc_t, lit0, nop);	 // write TC to PC19 and to F
	// F=0:  NOP                                    F=1:  T <- A
 	if_f_t(in_f(nop, to_dpl, ld, acc_t, lit0, nop),in_t(nop, to_t, add, acc_a, lit0, nop)); 
	*/

    // now copy bit 3 of bank nr to pc19
	ins6(nop, to_dpl, and_tst, acc_t, lit8, nop);  // dpl <- T and 8, set TC if bit was 1	
    ins6(tc_to_f, tc_to_sw_pc19, ld, acc_t, lit0, nop);	 // write TC to PC19 and to F

	/* 23-1-2026
	// add 1 to bank number. and then add 3. Same as xor 4 (modulo 8). Only when F=0 (base RAM). 
 	if_f_t(in_f(nop, to_t, xor, acc_t, lit4, nop),in_t(nop, to_t, xor, acc_t, lit0, nop));
	*/
	// 23-1-2026
	// F=0 (base): add 1 to bank number. and then add 3. Same as xor 4 (modulo 8).
	// F=1 (2nd 512k): add 1, modulo 8. Means first reset bit3, and set it again after the increment.
 	if_f_t(in_f(nop, to_t, xor, acc_t, lit4, nop),in_t(nop, to_t, res2, acc_t, lit8, nop));
 	if_f_t(in_f(nop, to_t, xor, acc_t, lit0, nop),in_t(nop, to_t, add, acc_t, lit1, nop));
 	if_f_t(in_f(nop, to_t, xor, acc_t, lit0, nop),in_t(nop, to_t, or, acc_t, lit8, nop));	
	// 23-1-2026 end. This makes it just fit in 16 cycles.

	ins6(nop, to_dpl, add, acc_t, lit0, nop);
	// BNK register is special. 4th parameter to 'ins6' must be acc_a.
	ins6(nop, to_bnk, ld, acc_a, dpl, nop); // also writes dph. uses acc_a.
	// 9-3-2025 ins6(nop, to_mem, ld, acc_t, reg_bank_dp, nop); // 22-11-2024 save a copy of the selected bank
	ins6(irq_to_f, to_mem, ld, acc_t, reg_bank_dp, nop); // 22-11-2024 save a copy of the selected bank	. 9-3 irq_to_f

    // now copy highest bit of bank nr to pc18
	ins6(nop, to_dpl, and_tst, acc_t, lit4, nop);  // dpl <- T and 4, set TC if bit was 1	
    ins6(nop, tc_to_sw_pc18, ld, acc_t, lit0, nop);	 // write TC to PC18

	

	final(irq_to_f, to_t, ld, acc_a, lit0, nop); // fetch next Z80 instruction
    print_cycles();
  }
  

//--- Read-Modify-Write instructions ----

function ins_inc(op, name, mode) { ins_rmw(op, name, inc, mode, upd_nz); }
function ins_dec(op, name, mode) { ins_rmw(op, name, dec, mode, upd_nz); }

function ins_asl(op, name, mode) { ins_rmw(op, name, asl, mode, upd_nzc); }
function ins_lsr(op, name, mode) { ins_rmw(op, name, lsr, mode, upd_nzc); }
function ins_rol(op, name, mode) { ins_rmw(op, name, rol, mode, upd_nzc); }
function ins_ror(op, name, mode) { ins_rmw(op, name, ror, mode, upd_nzc); }

//--- Regular arithmetic and logic ---

function ins_adc(op, name, mode) { ins_main(op, name, adc, mode, upd_nzc); }
function ins_sbc(op, name, mode) { ins_main(op, name, sbc, mode, upd_nzc); }

function ins_and(op, name, mode) { ins_main(op, name, and, mode, upd_nz); }
function ins_ora(op, name, mode) { ins_main(op, name, or , mode, upd_nz); }
function ins_eor(op, name, mode) { ins_main(op, name, xor, mode, upd_nz); }


//-----------------------------------------------------

//	Z80 functions

//----------------------------------------------------

// http://jgmalcolm.com/z80/download/z80.txt

function z80_opcode(page, opc, name, dst, src) { opcode_page(page, opc, name, dst, src); }


// Z80 CB group operations. Input is 'src', output in register 'to' (A or T)

function z80_shift(nop, to, operation, acc, src, upd, isfinal)  // CB group shifts and '8080' shifts
{
	if (operation == rla) { operation = rol; }  // to 6502 name
	else if (operation == rl) { operation = rol; }  // to 6502 name ROL: C <- [76543210] <- C
	else if (operation == rra) { operation = ror; }  // to 6502 name
	else if (operation == rr) { operation = ror; }  // to 6502 name ROR: C -> [76543210] -> C
	else if (operation == rrca) { operation = rrc; }  // 15-6

	else if (operation == sla) { operation = asl; }  // to 6502 name ASL: C <- [76543210] <- 0
	else if (operation == srl) { operation = lsr; }  // to 6502 name LSR: 0 -> [76543210] -> C

	// new 15-6. Handle all right-shifting operations (with a 256-byte table at zero page in RAM bank 1)
	if ((operation == ror) || (operation == lsr) || (operation == rrc) || (operation == sra)) // 
	{  // 23-7 insert section for simple case
		if ((isfinal) && (to == to_a) && (operation == lsr) && (upd == upd_c))  // 21-6
		{
			// 3-7-2025 loading of DPH blocked R0 to CY
			ins6(nop,to_dph,ld,acc_t,lit1,nop) ;  // 24-6-2025 new shr 
			ins6(irq_to_f, to_dpl, xor, acc_a, lit0, nop);  // first copy A to dpl. 20-7 xor, irq					  
			// 15-10-2023 no upd_c in last cycle
			ins6(nop, to, shrnew, acc_t, ext, upd); // get shifted data			
			final(irq_to_f, to_t, ld, acc_t, lit0, nop);  // nop 2-12 upd_f, irq_to_f			
			return; // end simple case
		}

		if (src==ext)  // 24-06-2025  special section for indirect
		{ // insert indirect (HL) (IX+n), (IY+n) here

		// save PCH, PCL ? Yes, done below.
	
		ins6(nop,to_t,ld,acc_t,pcl,nop); // get pcl
		ins6(nop, to_mem, ld, acc_t, reg_tl, nop);  // save pcl		

		// 5-11 moved to here
		var fill_f = c_to_f;
		if (operation == lsr) fill_f = irq_to_f;

		if (operation == sra) 	// shift right arithmetic  [77654321] -> C
		{
			// 5-11-2023  use tc instead of C.  2-12 added upd_f
			if (src == reg_a) // 23-7
			    { ins6(nop, to_t, asl, acc_t, src, nop); } // to T (unused), bit7 to TC // 10-5-2025 was wrong, not use to_dpl !
			fill_f = tc_to_f;
		}

		// get data to be shifted to dpl
		// PROBLEM fill_f can check C, but there must be one instruction inserted after C is written !
		// Ok, problem solved. 5-11
	
		if (operation == rrc) {
			ins6(fill_f, to_pch, ld, acc_t, src, nop);  // get data to be shifted to dpl, from reg or (hl) 21-7 irq. 24-6-2025, to pch

			// note that the R0 bit is bit0 of result bus in previous cycle !
			// 12-10-2023  note that r0 is inverted !
			
			ins6(r0_to_f, to_t, ld, acc_t, src, nop); //	just to obtain bit0 in F	24-6-2025 new shr, use src because this cycle determines R0 for main shift.

			// bit0 was put in cy (with fill_f) and will finally be in bit7				 
		}
		else {
			ins6(fill_f, to_pch, ld, acc_t, src, nop);  // get data to be shifted to dpl, from reg or (hl) 21-7 irq. 24-6-2025, to pch
		}

		// now the first PC byte was written, we can save the other byte
		ins6(cond_r0,to_t,ld,acc_t,pcl,upd); // get pch. 	also put R0, from prev cycle, into C
		ins6(nop,to_mem, ld, acc_t, reg_th, nop);  // save pch	

		// put the 256-byte page nr in pch
		ins6(nop, to_pch, ld, acc_t, lit1, nop); // new 24-6-2025
	
		var acc = acc_t;
		if (to == to_a) acc = acc_a; // use A or T ?

		// Now comes the main right-shift instruction
		// note that for SHR, DPL must be on the result bus in the previous cycle to get bit0 to CY !		  

		ins6(nop, to, shrnew, acc_t, pc_ind, nop);  // get shifted data from table, bit0 to CY.	24-6-2025 use PC !

		ins6(nop, to_pch, ld, acc_t, reg_tl, nop);  // restore pcl
		ins6(nop, to_pch, ld, acc_t, reg_th, nop);  // restore pch

		// Now, put a value in bit7, and might have to update N and Z flag.
		if (upd == upd_c) { // no NZ update	
			// 20-7-2023
			if (isfinal) {
				ins6(next_m, nop, nop, nop, nop, nop);  // that's only for operand = A
			}
			// 20-7-2023 we will use XOR to set bit7, that allows us to write flag F at the same time

			// 12-10-2023 For rrc, r0 is in f, but it is inverted !
			if (operation == rrc)  // put /r0 in bit7, for RRC  2-12 added upd_f
			{
				if_f_t(in_f(irq_to_f, to, xor, acc, reg_128, nop), in_t(delay_m, nop, nop, nop, nop, nop)); // put cy in bit 7
				f_is_irq = 1;
			}  // both delay_m and irq_to_f will leave F equal to IRQ
			else
				if (operation != lsr)  // put cy in bit7, for ROR and RRC  2-12 added upd_f
				{
					if_f_t(in_f(delay_m, nop, nop, nop, nop, nop), in_t(irq_to_f, to, xor, acc, reg_128, nop)); // put cy in bit 7
					f_is_irq = 1;
				} // both delay_m and irq_to_f will leave F equal to IRQ
		}
		else // with NZ update  21-6
		{ 
			// 12-10-2023 For rrc, r0 is in f, but it is inverted !
			if (operation == rrc)  // put cy in bit7, for ROR and RRC
			{	if_f_t(in_f(irq_to_f, to, xor, acc, reg_128, upd_nz), in_t(delay_m, nop, nop, nop, nop, nop)); // put cy in bit 7
				f_is_irq = 1;
			}
			else
				if (operation != lsr)  // put cy in bit7, for ROR and RRC (cy was put in F with fill_f)
				{	if_f_t(in_f(delay_m, nop, nop, nop, nop, nop), in_t(irq_to_f, to, xor, acc, reg_128, upd_nz)); // put cy in bit 7
					f_is_irq = 1;
				}

			if (isfinal)
				final(irq_to_f, to_mem, ld, acc, reg_z, nop);  // 21-6 store z, 20-7 add irq_to_f 2-12 upd_f
			else {
				ins6(nop, to_mem, ld, acc, reg_z, nop);  // 20-7 store z
				}
		}
		}
		else
		{ // non-indirect

		ins6(nop,to_dph,ld,acc_t,lit1,nop) ;  // 24-6-2025 new shr

		// 5-11 moved to here
		var fill_f = c_to_f;
		if (operation == lsr) fill_f = irq_to_f;

		if (operation == sra) 	// shift right arithmetic  [77654321] -> C
		{	// 5-11-2023  use tc instead of C.  
			if (src == reg_a) // 23-7
			{ ins6(nop, to_dpl, add, acc_a, reg_128, nop); }  // to dpl (unused), bit7 to TC
			
			else { ins6(nop, to_t, asl, acc_t, src, nop); } // to dpl (unused), bit7 to TC // 10-5-2025 was wrong, not use to_dpl !
			fill_f = tc_to_f;
		}

		//var setupd_f = upd_f;

		// get data to be shifted to dpl
		// PROBLEM fill_f can check C, but there must be one instruction inserted after C is written !
		// Ok, problem solved. 5-11
	
		if (operation == rrc) {
			if (src == reg_a) // 23-7  2-12 upd_f added
			{
				ins6(fill_f, to_dpl, xor, acc_a, lit0, nop);  // first copy A to dpl. 20-7 xor, irq				
			}
			else ins6(fill_f, to_dpl, ld, acc_t, src, nop);  // get data to be shifted to dpl, from reg or (hl) 21-7 irq
			// note that the R0 bit is bit0 of result bus in previous cycle !
			// 12-10-2023  note that r0 is inverted !
			ins6(r0_to_f, to_dpl, ld, acc_t, dpl, nop); //	just to obtain bit0 in F
			// bit0 was put in cy (with fill_f) and will finally be in bit7				 
		}
		else {
			if (src == reg_a) // 23-7 
				{ ins6(fill_f, to_dpl, xor, acc_a, lit0, nop);  // first copy A to dpl. 20-7 xor, irq		  				
				}
			else ins6(fill_f, to_dpl, ld, acc_t, src, nop);  // get data to be shifted to dpl, from reg or (hl) 21-7 irq
		}

		// if it is not RRC, we did set the upd_f bit for nothing. 'erase' it.
		//did_f_upd_f = 0; did_t_upd_f = 0; f_is_irq = 0; // 2-12 allow loading fake value in F. 22-5-2024 remove

		var acc = acc_t;
		if (to == to_a) acc = acc_a; // use A or T ?

		// Now, put a value in bit7, and might have to update N and Z flag.
		if (upd == upd_c) { // no NZ update	
			// Now comes the main right-shift instruction
			// note that for SHR, DPL must be on the result bus in the previous cycle to get bit0 to CY !		  
			
			ins6(nop, to, shrnew, acc_t, ext, upd);  // get shifted data from table, bit0 to CY. 2-12 upd_f	24-6-2025 new shr

			// 20-7-2023
			if (isfinal) {
				ins6(next_m, nop, nop, nop, nop, nop);  // that's only for operand = A
			}
			// 20-7-2023 we will use XOR to set bit7, that allows us to write flag F at the same time

			// 12-10-2023 For rrc, r0 is in f, but it is inverted !
			if (operation == rrc)  // put /r0 in bit7, for RRC  2-12 added upd_f
			{
				if_f_t(in_f(irq_to_f, to, xor, acc, reg_128, nop), in_t(delay_m, nop, nop, nop, nop, nop)); // put cy in bit 7
				f_is_irq = 1;
			}  // both delay_m and irq_to_f will leave F equal to IRQ
			else
				if (operation != lsr)  // put cy in bit7, for ROR and RRC  2-12 added upd_f
				{
					if_f_t(in_f(delay_m, nop, nop, nop, nop, nop), in_t(irq_to_f, to, xor, acc, reg_128, nop)); // put cy in bit 7
					f_is_irq = 1;
				} // both delay_m and irq_to_f will leave F equal to IRQ
		}
		else // with NZ update  21-6
		{ // Now comes the main right-shift instruction
			// note that for SHR, DPL must be on the result bus in the previous cycle to get bit0 to CY !		  
			
			ins6(nop, to, shrnew, acc_t, ext, upd);  // get shifted data from table, bit0 to CY. 2-12 upd_f	24-6-2025 new shr			

			// 12-10-2023 For rrc, r0 is in f, but it is inverted !
			if (operation == rrc)  // put cy in bit7, for ROR and RRC
			{	if_f_t(in_f(irq_to_f, to, xor, acc, reg_128, upd_nz), in_t(delay_m, nop, nop, nop, nop, nop)); // put cy in bit 7
				f_is_irq = 1;
			}
			else
				if (operation != lsr)  // put cy in bit7, for ROR and RRC (cy was put in F with fill_f)
				{	if_f_t(in_f(delay_m, nop, nop, nop, nop, nop), in_t(irq_to_f, to, xor, acc, reg_128, upd_nz)); // put cy in bit 7
					f_is_irq = 1;
				}

			if (isfinal)
				final(irq_to_f, to_mem, ld, acc, reg_z, nop);  // 21-6 store z, 20-7 add irq_to_f 2-12 upd_f
			else {
				ins6(nop, to_mem, ld, acc, reg_z, nop);  // 20-7 store z
				}
		}
		} // end of non-indirect
	}
	else // shift left	
	{
		if (src == reg_a) // 23-7
		{	ins6(irq_to_f, to_dpl, xor, acc_a, lit0, nop);  // first copy A to dpl. 20-7 xor, irq
			src = dpl;
		}

		//did_f_upd_f = 0; did_t_upd_f = 0; f_is_irq = 0; // 2-12 allow loading fake value in F. 22-5-2024 remove

		if ((operation == rlca) || (operation == rlc)) // rotate left circular C <- [65432107]
		{ // so test bit7, put it in C, and then shift it into 'itself'		    
			// 15-10-2023 getting C directly followed by using it... better use TC
			ins6(nop, to, asl, acc, src, nop); // put bit7 in TC, result to 'to' but unused. TC used in next cycle.
			operation = rol_tc; // rotate C into result, overwrite C			 
		}
		if (isfinal) {
			if (upd == upd_c) { 	// Now comes the instruction that does the left-shift
				ins6(nop, to, operation, acc, src, upd);
				final(irq_to_f, to_t, ld, acc_t, lit0, nop);  // 15-10-2023 nop, upd_c must not be last cycle 2-12 upd_f
			}
			else // upd_nzc
			{ // Now comes the instruction that does the left-shift
				ins6(nop, to, operation, acc, src, upd);
				final(irq_to_f, to_mem, ld, acc, reg_z, nop);  // 21-6 store z, 20-7 add irq_to_f 2-12 upd_f
			}
		}
		else if (upd == upd_nzc) {
			ins6(nop, to, operation, acc, src, upd);  // 2-12 upd_f
			ins6(irq_to_f, to_mem, ld, acc, reg_z, nop);  // 20-7 store z
		}
		else { ins6(nop, to, operation, acc, src, upd); }
	}
}


// Input is 'src', output in register 'to' (A or T)

function z80_cb(nop, to, operation, bitnr, src, upd, isfinal)   // for Z80 BIT SET and RES instructions
{
	var acc = acc_a;
	if (to == to_t) { acc = acc_t; }

	if ((operation == z80_bit) && (to == to_a))  // bit test. only affect z flag.
	{	make_bitmask(to_dpl, comp_val[bitnr]);
		ins6(nop, to_t, and, acc_a, src, upd);
		final(irq_to_f, to_mem, ld, acc_t, reg_z, nop);  // 21-6 store z, 20-7 add irq_to_f 2-12 upd_f
		return;
	}
	else if (operation == z80_bit) // bit test. only affect z flag.
	{	operation = and;
		to = to_t; acc = acc_t; // never write to acc_a in this case
		make_bitmask(to, comp_val[bitnr]);
	}
	else if (operation == z80_set)  // set bit. no flags affected.
	{	make_bitmask(to, comp_val[bitnr]);
		operation = or;
	}
	else if (operation == z80_res)  // reset bit. no flags affected.
	{	make_bitmask(to, comp_val[bitnr]);
		operation = res;   // Isetta alu-res function
	}

	if (isfinal) {
		if (upd != upd_z) { // problem line, for SET/RES in A. irq_to_f conflict with OR/RES
			// final(nop, to, operation, acc, src, upd_f); // 2-12 upd_f
			// So, do an exit without using 'final' that doesnt re-load irq
			ins6(nop, to_t, ld_ir, acc_t, pc_pp, page_z80); // next
			ins6(nop, to, operation, acc, src, nop); // instruction in delay. set upd_f
		}
		else {
			ins6(nop, to, operation, acc, src, upd);
			final(irq_to_f, to_mem, ld, acc, reg_z, nop);  // 21-6 store z, 20-7 add irq_to_f 2-12 upd_f
		}
	}
	else {
		ins6(nop, to, operation, acc, src, upd);
		if (upd == upd_z) ins6(nop, to_mem, ld, acc, reg_z, nop);  // 21-6 store z
	}
}

// function for generic handling of 8 bit instructions:

function z80_gen8(page, opc, name, operation, dst, src, upd) {
	z80_opcode(page, opc, name, dst, src);
	var adh = nop; var adl = nop;

	// Z80 Shift instructions. For (IX+n) don't add offset, that should be done in CB prefix.

	if ((operation == rla) || (operation == rra) ||
		(operation == rlca) || (operation == rrca) ||
		(operation == rl) || (operation == rr) ||
		(operation == rlc) || (operation == rrc) ||
		(operation == sla) || (operation == sra) ||
		(operation == srl)) {
		if (src != nop) error_msg("src must be nop for shift instruction");

		if (dst == ind_hl) { dst = ext; }  // dph/dpl should be filled in CB prefix, also for IX, IY.
		src = dst;
		if (dst == reg_a) { z80_shift(nop, to_a, operation, acc_t, src, upd, 1); }  // 23-7 from acc_a to A	    
		else {
			z80_shift(nop, to_t, operation, acc_t, src, upd, 0);  // from src. to T
			final(irq_to_f, to_mem, ld, acc_t, dst, nop);
		}   // store result back to src, 20-7 add irq_to_f 2-12 upd_f
		print_cycles();
		return;
	}

	// Z80 Bit test, Set and Reset instructions

	if ((operation == z80_bit) || (operation == z80_set) || (operation == z80_res)) { // dst=bitnr  src=target
		var bitnr = dst;
		// 2-12 for RES/SET ACC, load irq_to_f because that can't be done at the end.	
		if ((src == reg_a) && (operation != z80_bit))
			ins6(irq_to_f, to_dpl, xor, acc_a, lit0, nop); // copy A to dpl
		else {  }

		if (src == ind_hl) { src = ext; }  // dph/dpl should be filled in CB prefix, also for IX, IY.
		if (src == reg_a) { // 2-12 moved up: if (operation!=z80_bit) ins6(nop, to_dpl, add, acc_a, lit0, nop);  // first copy A to dpl
			z80_cb(nop, to_a, operation, bitnr, dpl, upd, 1);  // from dpl to A
		}
		else
			if (operation == z80_bit) { z80_cb(nop, to_t, operation, bitnr, src, upd, 1); }  // from src. to T
			else {
				z80_cb(nop, to_t, operation, bitnr, src, upd, 0);  // from src. to T
				final(irq_to_f, to_mem, ld, acc_t, src, nop);
			}   // back to src, 20-7 irq  2-12 upd_f    
		print_cycles();
		return;
	}

	if ((operation == inc) || (operation == dec)) {
		if (src != nop) error_msg("src must be nop for INC/DEC instruction");
		src = dst;
	}

	// for (IX+n), (IY+n), low index register byte is in T (done by prefix) but offset must be added.
	// This section calculates the target address and places it in dph/dpl
	if ((src == ind_ix_d) || (dst == ind_ix_d) ||
		(src == ind_iy_d) || (dst == ind_iy_d))	// 20-7-2023 added iy
	{
		// add displacement (SIGNED)
		// 25-7
		var register = reg_ixl;
		if ((src == ind_iy_d) || (dst == ind_iy_d)) register = reg_iyl;

		// 7-11-2023 new, put sign extension bit in tc/dtc
		ins6(nop, to_dpl, asl, acc_t, pc_ind, nop); // 25-7  dummy <- asl(pc)  bit7 to tc 
		ins6(nop, to_dpl, add, acc_t, pc_pp, nop); // 25-7  add (pc++) to IXL/IYL (in T), result to dpl 2-12 upd_f
		if ((src != ind_ix_d) && (src != ind_iy_d) && (dst != reg_a) && (src != reg_a))  // yes it can, imm or register
		{
			if (src == imm) // no IRQ test in imm when it goes to index-reg-halves
				 { ins6(dtc_to_f, to_t, ld, acc_a, pc_pp, nop); } // imm.  bit7 to F
			else { ins6(dtc_to_f, to_t, ld, acc_a, src, upd); }  // register. bit7 to F
			src = nop; // indicate src is handled
		}
		else ins6(dtc_to_f, to_t, ld, acc_t, lit0, nop); // get bit7 of displacement in F
		// no useful LD instruction can be at t7_to_f
		// 7-11-2023 end
		var register = reg_ixh;
		if (page == page_z80_iy) register = reg_iyh;

		if_f_t(in_f(nop, to_dph, inc_dtc, acc_t, register, nop),   // 16-10-2023  2-12 upd_f
			in_t(nop, to_dph, dec_dtc, acc_t, register, nop)); // adjust high byte 2-12 upd_f

		f_is_irq = 0; // 20-7-2023
	}
	if (src == ind_ix_d) { src = ext; }
	if (dst == ind_ix_d) { dst = ext; }
	if (src == ind_iy_d) { src = ext; } // 20-7-2023
	if (dst == ind_iy_d) { dst = ext; } // 20-7-2023
	// end (IX+n), (IY+d)

	if (src == ind_bc) { adh = reg_b; adl = reg_c; src = ext; }
	if (src == ind_de) { adh = reg_d; adl = reg_e; src = ext; }
	if (src == ind_hl) { adh = reg_h; adl = reg_l; src = ext; }

	if (dst == ind_bc) { adh = reg_b; adl = reg_c; dst = ext; }
	if (dst == ind_de) { adh = reg_d; adl = reg_e; dst = ext; }
	if (dst == ind_hl) { adh = reg_h; adl = reg_l; dst = ext; }

	// if needed, load high and low address from register pair into dph/dpl
	if (adl != nop) ins6(irq_to_f, to_dpl, ld, acc_a, adl, nop);
	if (adh != nop)
		if (adh == reg_h) // 2-12-2023
			 ins6(nop, to_dph, ld, acc_t, adh, nop); // 2-12 // 29-10-2024 change acc_a to acc_t
		else ins6(nop, to_dph, ld, acc_t, adh, nop); // 29-10-2024 change acc_a to acc_t

	if (src == abs) {
		ins6(irq_to_f, to_dpl, ld, acc_a, pc_pp, nop); // get low addr to dpl
		ins6(nop, to_dph, ld, acc_t, pc_pp, nop); // get high addr to dph // 29-10-2024 change acc_a to acc_t
		src = ext; // use dph/dpl as operand address(z80 extended addressing)
	}
	if (dst == abs) {
		ins6(irq_to_f, to_dpl, ld, acc_a, pc_pp, nop); // get low addr to dpl
		ins6(nop, to_dph, ld, acc_t, pc_pp, nop); // get high addr to ddh // 29-10-2024 change acc_a to acc_t
		dst = ext; // use dph/dpl as operand address(z80 extended addressing)
	}

	// handle LD A,src and OP A,src  (also INC A and DEC A )

	if (dst == reg_a) {
		var dst_register = to_a;
		if (operation == cp) dst_register = to_t; // 5-11-2023

		if ((src == imm) && (operation != ld)) src = pc_pp; // new 21-6
		else if (src == imm) { ins6(irq_to_f, to_dpl, ld, acc_a, pc_pp, nop); src = dpl; } // get imm to dpl  

		// XOR a,a was replaced by LD 0. But that does a cpl-cy ! Replace by AND lit0
		if (src == reg_a) {
			if ((operation == and) || (operation == or)) { operation = or; src = lit0; }  //fast AND A,A and OR A,A by doing OR A,#0 (used to set flags)
			else if (operation == xor) { operation = and; src = lit0; } // XOR A, A becomes AND A,#0
			else { // when the operand is A, put it in dpl
				ins6(irq_to_f, to_dpl, xor, acc_a, lit0, nop); src = dpl;
			} // reg_a to dpl. irq_to_f.  20-7-2023  2-12 upd_f		   
		}

		irqf = irq_to_f; // 20-7

		if ((operation == sub) || (operation == sbc) || (operation == cp)) // these need a final complement-carry
		{
			if (operation == sbc) {
				ins6(c_to_f, to_t, ld, acc_t, lit0, nop);   // nop, c to F 15-10-2023
				if_f_t(in_f(nop, dst_register, sub, acc_a, src, upd), // if cy was 0, sub
					in_t(nop, dst_register, sub_0, acc_a, src, upd));   // if cy was 1, sub_0 (borrow)
			}
			else {				
				ins6(nop, dst_register, sub, acc_a, src, upd);  // do sub  5-11  
			}
			// write reg_V must be directly after the add or sub operation						
			ins6(irq_to_f, to_mem, inp, acc_t, reg_v, nop); // 15-10-2023 write v, and delay between upd_c and cpl_c30-6-2024 irq_to_f
			
			// 30-6-2024 test interrupt. F=0 IRQ active,   F=1  IRQ not active
			if_f_t(in_f(interrupt_m, nop, nop, nop, nop, cpl_c), in_t(next_m, nop, nop, nop, nop, cpl_c));	// 30-6-2024

			if (operation == cp)  // 2-12 added upd_f
			{ ins6(irqf, to_mem, ld, acc_t, reg_z, nop); }  // write result of subtract to zero-register
			else { ins6(irqf, to_mem, ld, acc_a, reg_z, nop); }
		}
		else if ((operation == add) || (operation == adc)) {			

			ins6(nop, dst_register, operation, acc_a, src, upd);  // do add or adc	2-12 upd_f
			ins6(irq_to_f, to_mem, inp, acc_t, reg_v, nop);  // write overflow indicators to reg_v 19-7
			final(irqf, to_mem, ld, acc_a, reg_z, nop);  // 21-6 store z, 20-7 add irqf 2-12 upd_f
		}
		else if (operation == xor) {
			
			ins6(nop, dst_register, operation, acc_a, src, upd);  // do xor. It does not clear C

			ins6(next_m, nop, nop, nop, nop, clr_c);		// fetch new opcode. clr_c (not in last cycle)
			ins6(irqf, to_mem, ld, acc_a, reg_z, nop);  // 21-6 store z  2-12 upd_f
		}
		else if (operation == ld)  // load ACC from src
		{ 
			if (upd != nop) error_msg("load ACC from src, upd must be nop");
			// 2-12 It is possible that no cycle was done yet in this instruction (example, LD a,b)
			// for that case, the 'next' or 'interrupt' will still be chosen correctly, but during
			// that instruction a fake condition will go into F. But the last instruction does not
			// depend on F, and will load IRQ to F at the end of the instruction.			
			final(irqf, dst_register, operation, acc_a, src, nop);
		}
		else {  // Do an operation (with dst=A) that was not handled in one of the above cases
			ins6(nop, dst_register, operation, acc_a, src, upd);
			final(irqf, to_mem, ld, acc_a, reg_z, nop);  // 21-6 store z, 20-7 add irqf 2-12 upd_f
		}
		print_cycles();
		return;
	}

	// handle LD dst,src and INC/DEC.  via T register, but don't use T register if src == A

	// dst is now always a memory location or register in memory.

	if ((operation == inc) || (operation == dec)) {		

		ins6(nop, to_t, operation, acc_a, src, upd);  // INC or DEC

		ins6(irq_to_f, to_mem, ld, acc_t, reg_z, nop);  // 20-7 store z (for inc or dec)

		final(irq_to_f, to_mem, ld, acc_t, dst, nop);  // now write T or A to dst 2-12 upd_f
		print_cycles();
		return;
	}
	if (operation == ld) {
		var register_a_t = acc_t;

		var irqf = irq_to_f; // 20-7-2023

		// first read the source into T (or perhaps it is already in A)
		if (src == imm) { ins6(irq_to_f, to_t, ld, acc_a, pc_pp, nop); } // get imm to t	 
		else if (src == reg_a) { register_a_t = acc_a; }	// src is already in A

		// In some cases, the src is already in T ( ixh, ixl etc). Don't have to load in that case.
		else if (src != nop) { ins6(irq_to_f, to_t, operation, acc_a, src, upd); }  // LD

		// 2-12 It is possible that no cycle was done yet in this instruction (example, LD b,a)
		// for that case, the 'next' or 'interrupt' will still be chosen correctly, but during
		// that instruction a fake condition will go into F. But the last instruction does not
		// depend on F, and will load IRQ to F at the end of the instruction.

		final(irq_to_f, to_mem, ld, register_a_t, dst, nop);  // now write T or A to dst 2-12 upd_f
		print_cycles();
		return;
	}


	error_msg("z80_gen8 invalid operand combination");
}


function z80_ins8(opc, name, operation, dst, src, upd)  // might generate also ix/iy instructions
{
	z80_gen8(page_z80, opc, name, operation, dst, src, upd);  // basic operation

	if (src == ind_hl) {
		z80_gen8(page_z80_ix, opc, name, operation, dst, ind_ix_d, upd);
		z80_gen8(page_z80_iy, opc, name, operation, dst, ind_iy_d, upd);
	}
	else if (dst == ind_hl) {
		z80_gen8(page_z80_ix, opc, name, operation, ind_ix_d, src, upd);
		z80_gen8(page_z80_iy, opc, name, operation, ind_iy_d, src, upd);
	}
	// support the officially undocumented use of IX/IY register halves:

	// What if both operands are a L or H ? Have to find out.
	// new 30-4-2025: (found out)
	else if ((dst == reg_l) && (src == reg_h)) {
		z80_gen8(page_z80_ix, opc, name, operation, reg_ixl, reg_ixh, upd);
		z80_gen8(page_z80_iy, opc, name, operation, reg_iyl, reg_iyh, upd);
	}
	else if ((dst == reg_h) && (src == reg_l)) {
		z80_gen8(page_z80_ix, opc, name, operation, reg_ixh, reg_ixl, upd);
		z80_gen8(page_z80_iy, opc, name, operation, reg_iyh, reg_iyl, upd);
	}
	// 30-4-2025 end

	else if (src == reg_h) {
		z80_gen8(page_z80_ix, opc, name, operation, dst, reg_ixh, upd);
		z80_gen8(page_z80_iy, opc, name, operation, dst, reg_iyh, upd);
	}
	else if (dst == reg_h) {
		z80_gen8(page_z80_ix, opc, name, operation, reg_ixh, src, upd);
		z80_gen8(page_z80_iy, opc, name, operation, reg_iyh, src, upd);
	}
	else if (src == reg_l) {
		z80_gen8(page_z80_ix, opc, name, operation, dst, reg_ixl, upd);
		z80_gen8(page_z80_iy, opc, name, operation, dst, reg_iyl, upd);
	}
	else if (dst == reg_l) {
		z80_gen8(page_z80_ix, opc, name, operation, reg_ixl, src, upd);
		z80_gen8(page_z80_iy, opc, name, operation, reg_iyl, src, upd);
	}
}

//---- functions for 16-bit instructions ----


// Status register Z80:  S Z - H - V N C  But in the Isetta, sign flag is called N as in 6502. So it becomes:

//                 7 6 5 4 3 2 1 0
// Flags register: N Z - - - - - C  // where N is the sign flag. This sequence used for push and pop.
//                       5 4 3 2 1  // as stored in reg_flags


// z80_move8 is for moving from or to the T or A register, or from or to the Z80 flags (for push, pop).
// in case of flags, src can not be A or T. dst can only be T
// dst can also be pch or t, for jp (hl)
// z80_move8 is only used as a part of 16-bit instructions

function z80_move8(dst, src, isfinal, check_irq) {
	if (src == reg_flags)  // for PUSH. Uses dpl, dpl may not contain stackpointer
	{ // 4-7-2023
		// V state in reg_v, relevant bits: 00110001
		// Pack flags NVZC into one byte: (to T register)
		ins6(nop, to_dpl, rol, acc_t, reg_v, nop);  // get V bits, shift left -VV---VC  and put cy in bit0 2-12 upd_f

		ins6(n_to_f, to_t, ld, acc_t, reg_128, nop);      // bit7 in t, n flag to F

		// F: reset bit 7                        T: set bit 7
		if_f_t(in_f(nop, to_dpl, res, acc_t, dpl, nop), in_t(nop, to_dpl, or, acc_t, dpl, nop)); // reset or set bit7

		// we now have NVV---VC (in DPL)

		ins6(nop, to_dph, dec, acc_t, reg_z, nop); // Z state to TC (inverted). For Z80, always from reg_z. 2-12 upd_f
		ins6(tc_to_f, to_t, ld, acc_t, lit4, nop);      // bit2 in t, tc_flag to F

		//    F: reset bit2                        T: set bit2   // Bit2 becomes NOT-Z
		if_f_t(in_f(nop, to_t, res, acc_t, dpl, nop), in_t(nop, to_t, or, acc_t, dpl, nop)); // set or reset bit2

		// final result NVV--ZVC in T register (Z is inverted)

		if (dst != to_t) error_msg("for flags, dst must be T");
		
		return;
	}

	if (dst == reg_flags)  // for POP. uses dpl. 						
	{ // 5-7-2023 storage format:  NVV--ZVC  (Z is inverted)
		
		ins6(nop, to_t, ld, acc_t, src, upd_n);    // get flags, update N flag
		ins6(nop, to_t, and, acc_t, lit4, nop); // AND with value 0x04  00000100 to get NOT-Z
		ins6(nop, to_mem, ld, acc_t, reg_z, nop);  // store the z condition in register_z
	 
		ins6(nop, to_dpl, ld, acc_t, src, nop);    // get flags to dpl

		ins6(cond_r0, to_dph, ld, acc_t, lit1, upd_c);  //  8-8-2025 dhp <-1, move R0 to  C	

		// 24-6-2025 the V flag will not be restored !!!  Now DPH must also be filled, it will be one cycle too long !!!!
		// 25-6-2025 but have to restore CY !
		
		ins6(nop, to_t, shrnew, acc_t, ext, nop); // 8-8-2025 do a right shift, and have V in position
		
		ins6(nop, to_mem, ld, acc_t, reg_v, nop);  // store the three v flags // 8-8-2025 

		// 8-8-2025 will be one cycle too long, solve by jp to STSP at end of pop AF.

		// total for pop AF now: 16 cycles	

		return;
	}
	if ((dst == to_t) || (dst == to_a) || (dst == to_pch) || (dst == to_dph)) {
		if (isfinal) { ins6(next_m, nop, nop, nop, nop, nop); } // get next instruction	  
		// For an index register, the prefix has put IXL or IYL in T. In that case, nothing
		// has to be done here.
		if (((src == reg_ixl) || (src == reg_iyl)) && (dst == to_t)) { return; }

		ins6(check_irq, dst, ld, acc_t, src, nop); // 20-7-2023 src to T
	}
	else
		if ((src == acc_t) || (src == acc_a)) {
			if (isfinal) { final(check_irq, to_mem, ld, src, dst, nop); }   // 20-7-2023 2-12 upd_f
			else ins6(check_irq, to_mem, ld, src, dst, nop);	  // 20-7-2023	  
		}
		else { error_msg("move8 invalid operands"); }

} // end z80_move8


function pair_low(pair)  // get low byte of a register pair
{
	var dst = pair;
	if (pair == pair_bc) { dst = reg_c; }
	if (pair == pair_de) { dst = reg_e; }
	if (pair == pair_hl) { dst = reg_l; }
	if (pair == pair_ix) { dst = reg_ixl; }
	if (pair == pair_iy) { dst = reg_iyl; }
	if (pair == pair_sp) { dst = reg_spl; }
	if (pair == pair_af) { dst = reg_flags; }
	if (dst == pair_pc) { dst = to_t; }

	if (dst == pair_th_tl) { dst = reg_tl; } // 11-1-2025
	return dst;
}

function pair_high(pair)  // get high byte of a register pair
{
	var dst = pair;
	if (pair == pair_bc) { dst = reg_b; }
	if (pair == pair_de) { dst = reg_d; }
	if (pair == pair_hl) { dst = reg_h; }
	if (pair == pair_ix) { dst = reg_ixh; }
	if (pair == pair_iy) { dst = reg_iyh; }
	if (pair == pair_sp) { dst = reg_sph; }
	if (pair == pair_af) { dst = reg_a; }
	if (dst == pair_pc) { dst = to_pch; } // writing to pch will first put lsb in t 

	if (dst == pair_th_tl) { dst = reg_th; } // 11-1-2025	
	return dst;
}


// z80_half16 generates the 8-bit part of a 16 bit instruction

// upper=0:  handle low byte, upper=1: handle high byte

function z80_half16(page, opc, name, operation, dst, src, upd, upper, isfinal) {
	if (upper) { src = pair_high(src); dst = pair_high(dst); }
	else { src = pair_low(src); dst = pair_low(dst); }

	var check_irq = irq_to_f;  // irq is checked when writing T, at the end of this function

	// exchange operands ?
	if (operation == ex)  // A will be saved/restored by the function that calls z80_half16
	{
		z80_move8(to_a, src, isfinal, nop);		  // src to A
		z80_move8(to_t, dst, isfinal, nop);       // dst to T
		z80_move8(src, acc_t, isfinal, nop);      // T to src
		
		ins6(nop, to_mem, ld, acc_a, dst, nop); //   3-12 A to dst
		return;
	}

	// for push AF and pop AF

	if (dst == reg_a) { z80_move8(to_a, src, isfinal, check_irq); return; }
	if (src == reg_a) { z80_move8(dst, acc_a, isfinal, check_irq); return; }
	if (dst == reg_flags) { z80_move8(reg_flags, src, isfinal, nop); return; }
	if (src == reg_flags) { z80_move8(dst, reg_flags, isfinal, nop); return; }

	if (operation == push) {
		ins6(nop, to_t, ld, acc_t, src, nop);  // 25-7 src register to T
		ins6(nop, to_mem, ld, acc_t, dst, nop);  // 25-7 T to dst (stack)
		return;
	}

	// handle LD dst,src

	if (src == imm) src = pc_pp; // 3-12-2023

	if (operation == ld) 
	{ 
		if (dst == to_pch) // for jp(hl)  ld pc,hl
		{  ins6(check_irq, to_pch, ld, acc_t, src, nop); // 20-7-2023 src to T  3-12
		    final(delay_m, nop, nop, nop, nop, nop);
			return;
		}
		else
			if (dst == to_t)  // for jp(hl)   ld pc,hl
			{  	ins6(nop, to_pch, ld, acc_t, src, nop); // 20-7-2023 src to T  3-12
				return;
			}
			else { 
				if (upper) // new 3-12
					ins6(nop, to_t, ld, acc_t, src, nop); // 20-7-2023 src to T  3-12
				else ins6(nop, to_t, ld, acc_t, src, nop); // 20-7-2023 src to T  3-12			 
			}
		z80_move8(dst, acc_t, isfinal, check_irq);   // The result is in T. Now store it into dst. 		   
	}
	else    // handle inc, dec, add, adc, sbc
	{
		if ((operation == inc) || (operation == dec) || (operation == inc_tc) || (operation == dec_tc)
			|| (operation == inc_dtc) || (operation == dec_dtc)) // 16-10-2023
		{
			if (upper) // new 3-12
				ins6(nop, to_t, operation, acc_t, src, upd);   // Do operation. Might update flags. 3-12 upd_f
			else ins6(nop, to_t, operation, acc_t, src, upd);
			z80_move8(dst, acc_t, isfinal, check_irq);   // The result is in T. Now store it into dst.
		}
		else // add, adc or sbc
		{
			var testzero = 0;
			if ((src == dst) && (operation == add)) // then it must be add hl,hl, can be done by shifting:
			{
				if (upper) {
					ins6(nop, to_t, rol_dtc, acc_a, dst, upd); // MSB (and update flags) // 16-10-2023 used _dtc
					z80_move8(dst, acc_t, isfinal, check_irq);  // 3-12
				}
				else {
					//did_f_upd_f = 0; did_t_upd_f = 0; f_is_irq = 0; // 2-12 allow loading fake value in F. 22-5-2024 remove
					ins6(nop, to_t, asl, acc_a, dst, nop); // LSB   3-12 upd_f
					z80_move8(dst, acc_t, isfinal, check_irq);  // 3-12			
				}				
				return;
			}

			if (upper)  // new 16-10-2023
			{
				if (operation == add) { operation = add_dtc; }
				if (operation == adc) { operation = add_dtc; testzero = 1; }
				if (operation == sbc) { operation = sub_dtc; testzero = 1; }
			}
		
			// first load destination to T

			// For IX/IY the lower byte is already in T (done by prefix), and invert is not used then.
			// 15-10-2023 cy to f	
			if (upper) { ins6(nop, to_t, ld, acc_a, dst, nop); } // 3-12
			else {
				if ((dst != reg_ixl) && (dst != reg_iyl)) { ins6(c_to_f, to_t, ld, acc_a, dst, nop); }				
			}

			// now add/adc/sbc the src to T

			// 15-10-2023 new, invert cy by having it in the F flag and do conditional subtract
			if (operation == sbc)  // only for the first byte of the SBC
			{
				if_f_t(in_f(nop, to_t, sub, acc_t, src, upd), // if cy was 0, sub 
					in_t(nop, to_t, sub_0, acc_t, src, upd));   // if cy was 1, sub_0 (borrow)
			}
			else ins6(nop, to_t, operation, acc_t, src, upd);
			// 15-10-2023 end

			if (testzero) // true for ADC/SBC but not for the '8080' ADD
			{ // 16 bit ADC/SBC update the Z flag. Make sure that also low result byte is tested.
				// these instructions always have dst=HL (no IX,IY). So can simply OR with L register.
				// But the ADD HL,pair instruction should not do this !
				ins6(nop, to_mem, inp, acc_t, reg_v, nop); // 20-5-2023 write overflow indicator
				if (operation == sub_dtc)  // 16-10-2023 _dtc was _tc
				{  // put result in register and complement carry
					ins6(nop, to_mem, ld, acc_t, dst, cpl_c);  // 21-7 irq	22-7 cpl_c			 
				}
				else ins6(nop, to_mem, ld, acc_t, dst, nop);  	// result to register  21-7 irq 3-12 no irq_to_f

				ins6(nop, to_t, or, acc_t, reg_l, upd_z);  // (msb OR lsb) to determine z flag  

				final(irq_to_f, to_mem, ld, acc_t, reg_z, nop);  // 21-6 store z, 20-7 irq 2-12 upd_f
				return;
			}

			if (upper) { z80_move8(dst, acc_t, isfinal, check_irq); }  // The result is in T. Now store it into dst.
			else z80_move8(dst, acc_t, isfinal, check_irq);
		}
	}

} // end z80_half16


function z80_cpl(opc, name)  // complement acc. No flags affected.
{
	z80_opcode(page_z80, opc, name, nop, nop);
	
	ins6(nop, to_dpl, dec, acc_t, lit0, nop); // 0xFF to dpl
	final(irq_to_f, to_a, xor, acc_a, dpl, nop); // A = A xor 0xFF, 20-7 irq 2-12 upd_f
	print_cycles();
}

function z80_neg(opc, name)  // negate acc
{
	z80_opcode(page_z80_ed, opc, name, nop, nop);
	
	ins6(nop, to_dpl, dec, acc_t, lit0, nop); // 0xFF to dpl 3-12 upd_f
	ins6(irq_to_f, to_dpl, xor, acc_a, dpl, nop);  // dpl = A xor 0xFF, 7-9 irq_to_f
	ins6(nop, to_a, inc, acc_t, dpl, upd_nzc);     // A = dpl + 1
	ins6(nop, to_t, add, acc_t, lit0, nop); // 15-10-2023 nop, time between upd_c and cpl_c

	ins6(nop, to_mem, ld, acc_a, reg_z, cpl_c);
	ins6(next_m, nop, nop, nop, nop, nop);		// fetch new opcode. cpl_c must not be in last cycle
	ins6(delay_m, nop, nop, nop, nop, nop);
	print_cycles();
	// Z80 manual: C is set if Accumulator was not 00h before operation; otherwise, it is reset.
	// I think that's not ok now. 7-9-2023 repaired (not tested yet)
}

function z80_ccf(opc, name)  // complement cy
{
	z80_opcode(page_z80, opc, name, nop, nop);

	ins6(next_m, nop, nop, nop, nop, cpl_c);		// fetch new opcode. cpl_c must not be in last cycle. 5-11
	ins6(delay_m, nop, nop, nop, nop, nop);
	print_cycles();
}

// The function z80_gen16 is used to generate a 16-bit Z80 instruction

function z80_gen16(page, opc, name, operation, dst, src, upd) {
	z80_opcode(page, opc, name, dst, src);

	if ((operation == inc) || (operation == dec)) {
		if (src != nop) error_msg("src must be nop for INC/DEC instruction");
		src = dst;
	}

	if ((operation == add) || (operation == adc) || (operation == sbc)) { // new section 3-12
		z80_half16(page, opc, name, operation, dst, src, nop, 0, 0);  // handle LSB
		z80_half16(page, opc, name, operation, dst, src, upd, 1, 1);  // handle MSB, update flags
		print_cycles();
		return;
	}

	// first handle some special cases

	if (operation == ex)  // exchange register pair ?
		if (src == pair_af) {
			// 4-12-2023 reduced from 12 to 11 cycles
			// first swap the accumulator
			ins6(nop, to_dpl, ld, acc_t, reg_a_alt, nop);  // dpl <- reg_a_alt
			ins6(nop, to_mem, ld, acc_a, reg_a_alt, nop);  // reg_a_alt <- A

			// The alt-flag register, F', is actually stored in two registers:
			// reg_f_alt    stores the N and Z flags
			// reg_f_alt_cy stores the C flag.
			// The V flag is not exchanged (yet?)

			// swap the Z and N flags. Assume that bit7 of Z register is the N flag.
			ins6(nop, to_t, ld, acc_t, reg_z, nop);   // T <- reg_z
			ins6(nop, to_a, ld, acc_t, reg_f_alt, nop);   // A <- reg_f_alt  2-12 upd_f
			ins6(c_to_f, to_mem, ld, acc_t, reg_f_alt, nop);   // reg_f_alt <- T, c_to_f
			ins6(nop, to_mem, ld, acc_a, reg_z, upd_n);   // reg_z <- A, upd_n

			// swap the C flag. C is stored in bit7
			ins6(nop, to_t, rol, acc_t, reg_f_alt_cy, upd_c);   // dummy <- rol(reg_f_alt_cy)
			// if F = true, set bit 7. Else reset it
			if_f_t(in_f(nop, to_t, ld, acc_t, lit0, nop), in_t(nop, to_t, ld, acc_t, reg_128, upd_f)); // put cy in bit 7 4-12 upd_f
			ins6(irq_to_f, to_mem, ld, acc_t, reg_f_alt_cy, nop);  // reg_f_alt_cy <- T  4-12 irq_to_f

			// finally restore the accumulator (was stored in dpl)
			final(irq_to_f, to_a, ld, acc_t, dpl, nop);   // A <- dpl 3-12 upd_f

			print_cycles();
			return;
		}
		else //exchange register pair	
		{
			ins6(nop, to_mem, ld, acc_a, reg_tl, nop);		// save A in temp reg_tl
			if (dst == ind_sp) // exchange with top of stack  ex (sp),hl
			{
				ins6(nop, to_dpl, ld, acc_a, reg_spl, nop); // get low addr sp to dpl
				ins6(nop, to_dph, ld, acc_t, reg_sph, nop); // get high addr sp to dph // 29-10-2024 change acc_a to acc_t
				z80_half16(page, opc, name, operation, ext, src, nop, 0, 0);  // exchange LSB's
				if (option_z80_align_sp == 1) { z80_half16(page, opc, name, operation, ext_msb, src, nop, 1, 0); }   // exchange MSB's  29-10-29
				else {
					ins6(nop, to_dpl, inc, acc_a, dpl, nop);    //  incr stackpt					
					ins6(nop, to_dph, inc_tc, acc_t, reg_sph, nop); // 8-11-2023  // 29-10-2024 change acc_a to acc_t
					z80_half16(page, opc, name, operation, ext, src, nop, 1, 0);    // exchange MSB's
				}
			}
			else	 // normal case, ex de,hl
			{	z80_half16(page, opc, name, operation, dst, src, nop, 0, 0);  // exchange LSB's
				z80_half16(page, opc, name, operation, dst, src, nop, 1, 0);  // exchange MSB's
			}
			final(irq_to_f, to_a, ld, acc_a, reg_tl, nop);		// restore A from temp reg_tl 2-12 upd_f, irq_to_f
			print_cycles();
			return;
		}


	// 10-11-2023 new for push af

	if ((operation == push) && (dst == pair_af))// push register pair af
	{ // new, this will handle AF
		// start with getting LSB to T if that are the flags

		if (dst == pair_af) { z80_half16(page, opc, name, ld, to_t, dst, nop, 0, 0); } // LSB, flags, to T because calculation needs dpl. 6 cycles.

		ins6(nop, to_dpl, dec, acc_a, reg_spl, nop); // get low addr sp, minus 1, to dpl 2-12 upd_f

		// next line will set F=0 if above dec(dpl) crosses page 
		no_f_write_error = 1;
		
		ins6(tc_to_f, to_dph, dec_tc, acc_t, reg_sph, nop); // get high addr sp to dph  // 10-11 add tc_to_f, 3-11-2024 use acc_t
		
		no_f_write_error = 0;

		ins6(nop, to_mem, ld, acc_a, ext, nop);  		// 10-11  store MSB from ACC to stack

		ins6(nop, to_dpl, dec, acc_a, dpl, nop);    //  dec stackpt  3-12 upd_f

		// next line will set F=0 if above dec(dpl) crosses page 
		// But if F is already 0, it will not change	

		// 10-11 next line has a problem. if page was crossed 1st time, dph must always be loaded with
		// decremented value (or not loaded at all because it already has the decr. value)

		no_f_write_error = 1;
			   
		if_f_t(in_f(l_to_f, to_dph, dec, acc_t, reg_sph, nop), // if false, re-load decremented sph		   
			in_t(tc_to_f, to_dph, dec_tc, acc_t, reg_sph, nop));   // if true, might decrement sph
		no_f_write_error = 0;
		// if F is false, DPH must be saved at the end.
		// if F is true, no update of sp-msb is needed

		ins6(nop, to_mem, ld, acc_t, ext, nop); // save T (LSB, flags) to stack

		if_f_t(in_f(nop, to_t, ld_ir, acc_t, lit8, page_z80_ix), // if false, jmp to STSP lit8 (page!) 21-11-2023

			in_t(nop, to_t, ld, acc_a, dpl, nop));   // if true, get dpl to T

		if_f_t(in_f(nop, to_t, dec, acc_a, reg_sph, nop), // if false, get sph-1 to T 3-12 upd_f
			in_t(next_m, nop, nop, nop, nop, nop));  // if true, next instruction

		ins6(irq_to_f, to_mem, ld, acc_t, reg_spl, nop);     // store T in SPL, (for F=1 only) 2-12 upd_f
		//  execution stops here. 15 cycles
		print_cycles();
		return;
	}

	// 3-11-2023 new fast PUSH, not for AF.
	if ((operation == push) && (dst != pair_af))// push register pair bc,de,hl,ix,iy,af
	{ 	// 30-6-2024
	    if (page == page_z80)
		  { // check irq
			ins6_chi(nop, to_dpl, dec, acc_a, reg_spl, nop); // get low addr sp, minus 1, to dpl
			ins6_pcmin1(nop, to_dph, dec_tc, acc_t, reg_sph, nop); // get high addr sp to dph  3-12 upd_f // 29-10-2024 change acc_a to acc_t
		  }		
        else // no irq check for IX, IY
		  {	ins6(nop, to_dpl, dec, acc_a, reg_spl, nop); // get low addr sp, minus 1, to dpl
			ins6(nop, to_dph, dec_tc, acc_t, reg_sph, nop); // get high addr sp to dph  3-12 upd_f // 29-10-2024 change acc_a to acc_t
		  }

		{	var dst_h = pair_high(dst);
			var dst_l = pair_low(dst);
			// next line will set F=0 if above dec(dpl) crosses page 
			ins6(dtc_to_f, to_t, ld, acc_t, dst_h, nop);    // get MSB of register to push, F <- dtc	
			ins6(nop, to_mem, ld, acc_t, ext, nop);  		// store MSB from t to stack
			ins6(nop, to_dpl, dec, acc_a, dpl, nop);    //  dec stackpt  3-12 upd_f
			// next line will set F=0 if above dec(dpl) crosses page 
			// But if F is already 0, it will not change	
			
			if_f_t(in_f(l_to_f, to_t, ld, acc_t, dst_l, nop), // if false, get LSB of register to push
				in_t(tc_to_f, to_t, ld, acc_t, dst_l, nop));   // if true, get LSB of register to push 		 		 
		}

		// if F is false, DPH needs decrement and must be saved at the end.
		// if F is true, no update of sp-msb is needed	  

		if_f_t(in_f(nop, to_dph, dec, acc_t, reg_sph, nop), // if false, conditional decr dph // 8-11-2023 // 29-10-2024 change acc_a to acc_t
			in_t(nop, to_mem, ld, acc_t, ext, nop));  // if true, save T (LSB) to stack

		if_f_t(in_f(nop, to_mem, ld, acc_t, ext, nop), // if false, save T (LSB) to stack
			in_t(nop, to_t, ld, acc_a, dpl, nop));   // if true, get dpl to T

		if_f_t(in_f(nop, to_t, ld, acc_a, dpl, nop), // if false, get dpl to T  3-12 upd_f
			in_t(next_m, nop, nop, nop, nop, nop));  // if true, next instruction

		// 3-12 
		if_f_t(in_f(irq_to_f, to_mem, ld, acc_t, reg_spl, nop), // if false  store T in SPL
			in_t(irq_to_f, to_mem, ld, acc_t, reg_spl, nop));  // if true, store T in SPL, last instruction here

		// if SP does not cross a page, execution stops here (10 cycles)

		ins6(nop, to_t, dec, acc_a, reg_sph, nop); // get high addr sp from dph to t	// 8-11-2023 

		final(irq_to_f, to_mem, ld, acc_t, reg_sph, nop);	// store T back in stackpt sph, 20-7 irq 3-12 upd_f
		// 13 cycles if a page was crossed
		print_cycles();
		return;
	}

	// 8-11-2023 this newest POP will not store to reg_SPH if not needed, and will not use dph as operand.
	// 5-11-2023 at the moment, the following code is only used for POP AF
	// 29-10-2023 next section only for unaligned stack (old, tested system)
	if (operation == pop) // pop register pair bc,de,hl,ix,iy,af
	{ 	// 30-6-2024
	    if (page == page_z80)
		  { // check irq
			ins6_chi(nop, to_dpl, ld, acc_a, reg_spl, nop); // get low addr sp to dpl
			ins6_pcmin1(nop, to_dph, ld, acc_t, reg_sph, nop); // get high addr sp to dph // 29-10-2024 change acc_a to acc_t
		  }		
        else // no irq check
		  { ins6(nop, to_dpl, ld, acc_a, reg_spl, nop); // get low addr sp to dpl
			ins6(nop, to_dph, ld, acc_t, reg_sph, nop); // get high addr sp to dph // 29-10-2024 change acc_a to acc_t
		  }

		z80_half16(page, opc, name, ld, dst, ext, nop, 0, 0);  // pop LSB
		// 15-6-2023 re-load stackpointer and increment it. Can now use dph/dpl to unpack flags (in pop LSB)
		ins6(nop, to_dpl, inc, acc_a, reg_spl, nop);    //  load and inc stackpt. create carry TC 3-12 upd_f

		// 9-11-2023
		no_f_write_error = 1;
		ins6(tc_to_f, to_dph, inc_tc, acc_t, reg_sph, nop); // 29-10-2024 change acc_a to acc_t
		no_f_write_error = 0;

		// F=0 no cy occurred		  F=1 cy occurred

		if (dst == pair_af) {
			
			// new

			ins6(nop, to_a, ld, acc_t, ext, nop);   // get ACC from stack

			ins6(nop, to_dpl, inc, acc_a, dpl, nop);	// dpl <- dpl + 1 	

			ins6(nop, to_t, ld_ir, acc_t, lit8, page_z80_ix); // jump to STPS (store stack pointer) in page_ix

			if_f_t(in_f(nop, to_t, inc_dtc, acc_t, reg_sph, nop),   // if false, T <- inc(sph) if there is a cy
				in_t(nop, to_t, inc, acc_t, reg_sph, nop)); // if true,  T <- inc(sph)	

			// end section of POP AF							
		}
		else {

			ins6(nop, to_t, inc, acc_a, dpl, nop);	// dpl + 1 to t	  3-12 upd_f
		
			// store T back in stackpt spl
			if_f_t(in_f(tc_to_f, to_mem, ld, acc_t, reg_spl, nop),   // if false, store T back in stackpt, tc to f. 			
				in_t(h_to_f, to_mem, ld, acc_t, reg_spl, nop)); // if true, store T back in stackpt 

			// F=0 no cy occurred		  F=1 cy occurred			
			ins6(nop, to_t, ld, acc_t, ext, nop); // get MSB byte from stack. 
			var reg_msb = pair_high(dst);

			if_f_t(in_f(next_m, nop, nop, nop, nop, nop),   // if false, get next instruction
				in_t(nop, to_mem, ld, acc_t, reg_msb, nop)); // if true, store in high register

			if_f_t(in_f(irq_to_f, to_mem, ld, acc_t, reg_msb, nop),   // if false, store in high register  3-12 upd_f
				in_t(nop, to_t, inc, acc_t, reg_sph, nop)); // if true,  T <- inc(sph)

			// if stack crossed page, two cycles more:
			final(irq_to_f, to_mem, ld, acc_t, reg_sph, nop); //  store T to SPH	3-12 upd_f
		}
		print_cycles();
		return;
	}

	// new 16-5-2023
	if ((operation == inc) && (page == page_z80) && (dst == pair_hl)) // for only 4 cycle INC HL
	{
		ins6(nop, to_t, inc, acc_t, reg_l, nop); // 3-12 upd_f
		ins6(tc_to_f, to_mem, ld, acc_t, reg_l, nop); // store incremented L register

		if_f_t(in_f(next_m, nop, nop, nop, nop, nop),   // if false, no carry, next
			in_t(nop, to_t, inc, acc_t, reg_h, nop)); // if true, inc H
		if_f_t(in_f(delay_m, nop, nop, nop, nop, nop),   // if false, no carry, delay
			in_t(next_m, nop, nop, nop, nop, nop)); // if true, next instruction
		ins6(irq_to_f, to_mem, ld, acc_t, reg_h, nop); // store incremented H, 20-7 added irq_to_f 3-12 upd_f
		print_cycles();
		return;
	}

	// now comes code for the more general cases

	if (src == abs)			// load register pair from absolute address  LD HL,(abs)
	{ // 9-11-2023 changed, dph no more used as operand (so no more dph <- inc(dph) )
		// 30-6-2024
	    if (page == page_z80)
		  { // check irq
		  	ins6_chi(nop, to_dpl, ld, acc_a, pc_pp, nop); // get low addr sp to dpl 3-12 upd_f
			ins6_pcmin1(r0_to_f, to_dph, ld, acc_t, pc_ind, nop); // 9-11 no pc-inc, high addr to dph, set F if addr aligned // 29-10-2024 change acc_a to acc_t
		  }		
        else
		  {	ins6(nop, to_dpl, ld, acc_a, pc_pp, nop); // get low addr sp to dpl 3-12 upd_f
			ins6(r0_to_f, to_dph, ld, acc_t, pc_ind, nop); // 9-11 no pc-inc, high addr to dph, set F if addr aligned // 29-10-2024 change acc_a to acc_t
		  }
		var dst_l = pair_low(dst);
		var dst_h = pair_high(dst);
		ins6(nop, to_t, ld, acc_t, ext, nop);  // get lsb
		ins6(nop, to_mem, ld, acc_t, dst_l, nop); // to register lsb

		if_f_t(in_f(nop, to_dpl, inc, acc_t, dpl, nop),   // if false, inc dpl			
			in_t(nop, to_t, ld, acc_t, ext_msb, inc_pc)); // 9-11 if true, get msb, increment pc

		if_f_t(in_f(nop, to_dph, inc_tc, acc_t, pc_pp, nop),   // 9-11 if false, conditional dph <- inc (pc++)
			in_t(next_m, nop, nop, nop, nop, nop)); // if true,  get next instruction

		if_f_t(in_f(nop, to_t, ld, acc_t, ext, nop),   // if false,  get msb
			in_t(irq_to_f, to_mem, ld, acc_t, dst_h, nop)); // if true, store MSB in high register 3-12 upd_f
		// if addr is word-aligned, execution has stopped here (7 cycles)
		final(irq_to_f, to_mem, ld, acc_t, dst_h, nop); // store MSB in high register  (9 cycles) 3-12 upd_f
		print_cycles();
		return;
	}
	if (dst == abs)		// store register pair to absolute address   LD (abs),HL
	{ // 9-11-2023 changed, dph no more used as operand (so no more dph <- inc(dph) )
		// 5-11-2023 new. Faster code if the address is aligned
		// 30-6-2024
	    if (page == page_z80)
		  { // check irq
		  	ins6_chi(nop, to_dpl, ld, acc_a, pc_pp, nop); // get low addr sp to dpl 3-12 upd_f
			ins6_pcmin1(r0_to_f, to_dph, ld, acc_t, pc_ind, nop); // 9-11 no pc-inc, high addr to dph, set F if addr aligned // 29-10-2024 change acc_a to acc_t
		  }		
        else
		  {	ins6(nop, to_dpl, ld, acc_a, pc_pp, nop); // get low addr sp to dpl 3-12 upd_f
			ins6(r0_to_f, to_dph, ld, acc_t, pc_ind, nop); // 9-11 no pc-inc, high addr to dph, set F if addr aligned // 29-10-2024 change acc_a to acc_t
		  }
		if (src == pair_th_tl)
		{   // 10-2-2025 2nd disable interupt for th-tl register (used in debugger)
  			ins6(nop,to_t,ld,acc_t,lit4, nop); // T <- 4
    		ins6(nop,to_t,res,acc_t,reg_irq, nop);    // T <- T res reg_irq (reset bit T in reg_irq)		
			ins6(nop,to_mem,ld,acc_t,reg_irq, nop); 		
		}
		var src_l = pair_low(src);
		var src_h = pair_high(src);

		if ((src_l != reg_ixl) && (src_l != reg_iyl)) // lsb of IX/IY is loaded in T by prefix
			ins6(nop, to_t, ld, acc_t, src_l, nop);  // get register lsb

		if_f_t(in_f(nop, to_mem, ld, acc_t, ext, nop),   // 9-11 if false, T to addr lsb
			in_t(nop, to_mem, ld, acc_t, ext, inc_pc)); // 9-11 if true,  T to addr lsb, increment pc

		if_f_t(in_f(nop, to_dpl, inc, acc_t, dpl, nop),   // if false, inc dpl
			in_t(nop, to_t, ld, acc_t, src_h, nop)); // if true, get register msb

		if_f_t(in_f(nop, to_dph, inc_tc, acc_t, pc_pp, nop),   // 9-11 if false, conditional dph <- inc (pc++)
			in_t(next_m, nop, nop, nop, nop, nop)); // if true,  get next instruction

		if_f_t(in_f(nop, to_t, ld, acc_t, src_h, nop),   // if false,  get register msb
			in_t(irq_to_f, to_mem, ld, acc_t, ext_msb, nop)); // if true, store MSB at high addr 3-12 upd_f
		// if addr is word-aligned, execution has stopped here (7 cycles)
		final(irq_to_f, to_mem, ld, acc_t, ext, nop); //  store MSB at high addr  (9 cycles)  3-12 upd_f
		print_cycles();
		return;
	}

	z80_half16(page, opc, name, operation, dst, src, nop, 0, 0);  // handle LSB

	if (operation == inc) { operation = inc_dtc; } // 16-10-2023 _dtc
	if (operation == dec) { operation = dec_dtc; } // 16-10-2023 _dtc

	z80_half16(page, opc, name, operation, dst, src, upd, 1, 1);    // handle MSB, update flags
	print_cycles();
}


function z80_exx(page, opc, name) {
	z80_opcode(page, opc, name, nop, nop);
	ins6(irq_to_f, to_t, ld, acc_t, reg_sel, nop); 			// get reg_sel to T

	// new 8-10-2023. Note that r0 goes through a HW inverter just before the condition selector.
	ins6(nop, r0_to_sw_exx, ld, acc_t, lit0, nop);  // r0 must be on result bus in prev cycle

	final(irq_to_f, to_t, ld, acc_t, lit0, nop);  // this is a nop  3-12 upd_f
	print_cycles();
}

function z80_hlt(page, opc, name) {    // 31-10-2024
	z80_opcode(page, opc, name, nop, nop);

	make_literal(to_t, 0x76) ;  // get HLT opcode in T register

	ins6(irq_to_f, to_mem, ld, acc_t, reg_th, nop); 			// put T in reg_th. Get interrupt flag.

	// if interrupt is active (low), handle interrupt. Else, jmp back to this HLT instruction

	if_f_t(in_f(interrupt_m, nop, nop, nop, nop, nop), in_t(nop, to_t, ld_ir, acc_t, reg_th, nop)); // F: do interrupt    T: jp back to HLT
	ins6(delay_m, nop, nop, nop, nop, nop);													   //  delay

	print_cycles();
}


function z80_prefix_dd(page, opc, name)			// prefix IX
{
	z80_opcode(page, opc, name, nop, nop);	
	// 30-6-2024 check interrupt
	ins6_chi(nop, to_t, ld_ir, acc_t, pc_pp, page_z80_ix); // 20-7 get next opcode, use page_z80_ix 3-12 upd_f
	ins6_pcmin1(irq_to_f, to_t, ld, acc_t, reg_ixl, nop);		   // 25-7  T <- ixl  3-12 upd_f, irq_to_f
	print_cycles();
}

function z80_prefix_fd(page, opc, name)			// prefix IY
{
	z80_opcode(page, opc, name, nop, nop);
	// 30-6-2024 check interrupt
	ins6_chi(nop, to_t, ld_ir, acc_t, pc_pp, page_z80_iy); // 20-7 get next opcode, use page_z80_iy 3-12 upd_f
	ins6_pcmin1(irq_to_f, to_t, ld, acc_t, reg_iyl, nop);		   // 25-7  T <- iyl  3-12 upd_f, irq_to_f
	print_cycles();
}

function z80_prefix_cb(page, opc, name)			// prefix CB for shift,bit,set,reset
{
	z80_opcode(page, opc, name, nop, nop);

	if ((page == page_z80_ix) || (page == page_z80_iy)) { // shift,bit,set,reset for (IX+d) and (IY+d). Add displacement.
		// displacement is SIGNED	  
		var register = reg_ixl;
		if (page == page_z80_iy) register = reg_iyl;

		// 7-11-2023 new, put sign extension bit in tc/dtc
		ins6(nop, to_dpl, asl, acc_t, pc_ind, nop); // 25-7  dummy <- asl(pc)  bit7 to tc
		ins6(nop, to_dpl, add, acc_t, pc_pp, nop); // 25-7  add (pc++) to IXL/IYL (in T), result to dpl 3-12 upd_f
		ins6(dtc_to_f, to_t, ld, acc_t, lit0, nop); // get bit7 of displacement in F
		// no useful LD instruction can be at t7_to_f
		// 7-11-2023 end	  

		var register = reg_ixh;
		if (page == page_z80_iy) register = reg_iyh;

		if_f_t(in_f(nop, to_dph, inc_dtc, acc_t, register, nop), // 16-10-2023
			in_t(nop, to_dph, dec_dtc, acc_t, register, nop)); // adjust high byte			 

		ins6(nop, to_t, ld_ir, acc_t, pc_pp, page_z80_cb); // get next opcode, use page_z80_cb 3-12 upd_f
		ins6(delay_m, nop, nop, nop, nop, nop); // 20-7-2023  delay_m will set F to irq	3-12 upd_f	  
	}
	else {
		// 30-6-2024 check interrupt
		ins6_chi(nop, to_dpl, ld, acc_t, reg_l, nop);	// for CB, put HL in dph/dpl	 
		ins6_pcmin1(nop, to_t, ld_ir, acc_t, pc_pp, page_z80_cb); // get next opcode, use page_z80_cb 3-12 upd_f		
		
		ins6(irq_to_f, to_dph, ld, acc_t, reg_h, nop);  // 20-7 add irq_to_f 3-12 upd_f
	}
	print_cycles();
}

function z80_prefix_ed(page, opc, name)			// prefix ED
{
	z80_opcode(page, opc, name, nop, nop);
  	// 30-6-2024 check interrupt 
	ins6_chi(nop, to_t, ld_ir, acc_t, pc_pp, page_z80_ed); // get next opcode, use page_z80_ed 3-12 upd_f
	ins6_pcmin1(delay_m, nop, nop, nop, nop, nop);			// nop  3-12 upd_f
	print_cycles();
}


function z80_int(op, name) 		// interrupt (at 0x80). 
{
	z80_opcode(page_z80_ed, op, name, nop, nop);

	ins6(nop, to_t, ld, acc_t, lit0, nop);	 // clear T	 
	f_is_irq = 0; // 20-7-2023 prevent that INTERRUPT will interrupt itself 

	ins6(irq_to_f, to_t, ld_ir, acc_t, reg_kb_state, page_reset);  // 10-4-2024 jp to KB device handler 
	ins6(delay_m, nop, nop, nop, nop, nop);
	print_cycles();
}

// INRZ at lit32 (0x20 in page_z80_ix), 15-6-2024
function z80_inrz(op, name) 		// interrupt at 0x20. It will retry the current instruction, doing PC = PC - 2 and then interrupt.
{	opcode_page(page_z80_ix, op, name, nop, nop);   // this one is in the ix page

	ins6(nop, to_t, ld, acc_t, pcl, nop);  // T <- pcl // 29-6-2024
    // new 15-6-2024
	ins6(nop, to_pch, sub_0, acc_t, lit1, nop);  // pch <- T - 2 
	ins6(nop, to_pch, dec_tc, acc_t, pcl, nop);  // pcl is now pch. conditionally dec pch, and pcl<-old_pch

    ins6(irq_to_f, to_t, ld_ir, acc_t, reg_128, page_reset); // goto z80_int
	ins6(delay_m, nop, nop, nop, nop, nop);

	print_cycles();
}


function z80_di(op,name)  // DI  disable interrupt
{	opcode_page(page_z80, op, name, nop, nop); 
    ins6(nop,to_t,ld,acc_t,lit8, nop); // T <- 8
    ins6(nop,to_t,res,acc_t,reg_irq, nop);    // T <- T res reg_irq (reset bit T in reg_irq)
	ins6(next_m, nop, nop, nop, nop, nop);
	ins6(nop,to_mem,ld,acc_t,reg_irq, nop); 
	print_cycles();
}

function z80_ei(op,name)  // EI  enable interrupt
{	opcode_page(page_z80, op, name, nop, nop); 
    ins6(nop,to_t,ld,acc_t,lit8, nop); // T <- 8
    ins6(nop,to_t,or,acc_t,reg_irq, nop);   // T <- T OR reg_irq
	ins6(next_m, nop, nop, nop, nop, nop);	
	ins6(h_to_f,to_mem,ld,acc_t,reg_irq, nop); 	 // 24-2-2025 no interrupt at start of next instruction
	print_cycles();
}

function z80_di2(op,name)  // DI  2nd disable interrupt  10-2-2025. ED 63
{	opcode_page(page_z80_ed, op, name, nop, nop); 
    ins6(nop,to_t,ld,acc_t,lit4, nop); // T <- 4
    ins6(nop,to_t,res,acc_t,reg_irq, nop);    // T <- T res reg_irq (reset bit T in reg_irq)
	ins6(next_m, nop, nop, nop, nop, nop);
	ins6(nop,to_mem,ld,acc_t,reg_irq, nop); 
	print_cycles();
}

function z80_ei2(op,name)  // EI  2nd enable interrupt  10-2-2025. ED 6B
{	opcode_page(page_z80_ed, op, name, nop, nop); 
    ins6(nop,to_t,ld,acc_t,lit4, nop); // T <- 4
    ins6(nop,to_t,or,acc_t,reg_irq, nop);   // T <- T OR reg_irq
	ins6(next_m, nop, nop, nop, nop, nop);
	ins6(h_to_f,to_mem,ld,acc_t,reg_irq, nop); 	 // 24-2-2025 no interrupt at start of next instruction
	print_cycles();
}

function z80_im(op,name)  // IM0 - IM2  are NOP's. LD R,A also. LD A,R gives a number (random ??)
{	opcode_page(page_z80_ed, op, name, nop, nop); 
	//ins6(next_m, nop, nop, nop, nop, nop); // 30-8-2025 moved down
	if (op == 0x5F) // ld A,R
	  { // 31-8-2025 kick the noise generator (used in "random"register R), also used in PSG
		ins6(nop,to_a,asl,acc_t,reg_noise_lsb,nop);  // A <- asl(noise_lsb)
		ins6(nop,to_t,rol_tc,acc_t,reg_noise_msb,nop);  // T <- rol_tc(noise_msb) 
		ins6(tc_to_f,to_mem,ld,acc_t,reg_noise_msb,nop); // noise_msb <- T, f <- tc

		if_f_t(in_f(nop,to_dpl,ld,acc_t,ext,bank2),     // F: dpl <- nextdpl  // toggle output bit
			in_t(nop,to_a,xor,acc_a,reg_psg_tmp,nop)  ); //  T: A <- A xor 0x2D (the constant is in reg_psg_tmp)

		ins6(nop,to_mem,ld,acc_a,reg_noise_lsb,nop);  // noise_lsb <- A 
		// noise generator end	
		
	    ins6(irq_to_f, to_a, add, acc_a, reg_snd_ptl, nop);   // 30-8-2025 improve random
	  }
	
	ins6(next_m, nop, nop, nop, nop, nop); // 30-8-2025 new here
	ins6(delay_m, nop, nop, nop, nop, nop);
	print_cycles();
}


function z80_ld_ia(op,name)  // 2-10-2024  LD I,A
{	opcode_page(page_z80_ed, op, name, nop, nop); 
	ins6(next_m, nop, nop, nop, nop, nop);
	ins6(nop, to_mem, ld, acc_a, reg_i, nop);
	print_cycles();
}

function z80_ld_ai(op,name)  // 2-10-2024  LD A,I
{	opcode_page(page_z80_ed, op, name, nop, nop); 
	ins6(next_m, nop, nop, nop, nop, nop);
	ins6(nop, to_a, ld, acc_t, reg_i, nop);
	print_cycles();
}


// 2-10-2024 New.  A nornal RET can make a JMP to the debugger, if enabled. The RETI will not do that.
function z80_reti(op, name, condition, polarity) 		// RETI  return from interrupt. Code is the same as RET. But no interrupt checking.
{	opcode_page(page_z80_ed, op, name, nop, nop);   

	// 30-6-2024 removed. 2-10-2024 for RETI, put back again.
	ins6(condition, to_dpl, ld, acc_a, reg_spl, nop); // get low addr sp to dpl
	{	if (polarity == true) { // when return should occur if flag is true:
			if_f_t(in_f(next_m, nop, nop, nop, nop, nop), in_t(nop, to_dph, ld, acc_t, reg_sph, nop)); // get high addr sp to dph // 29-10-2024 change acc_a to acc_t
			if_f_t(in_f(delay_m, nop, nop, nop, nop, nop), in_t(nop, to_pch, ld, acc_t, ext, nop)); // 10-11-2023
		}
		else { // when return should occur if flag is false:
			if_f_t(in_f(nop, to_dph, ld, acc_t, reg_sph, nop), in_t(next_m, nop, nop, nop, nop, nop)); // get high addr sp to dph // 29-10-2024 change acc_a to acc_t
			
			if_f_t(in_f(irq_to_f, to_pch, ld, acc_t, ext, nop), in_t(delay_m, nop, nop, nop, nop, nop)); // 30-6-2024 add irq_to_f
		}
	}
	// stackpt is in dph/dpl. LSB has been popped from stack into T    
	ins6(nop, to_dpl, inc, acc_a, reg_spl, nop);    //  load and inc stackpt. create carry TC 3-12 upd_f

	// 9-11-2023
	no_f_write_error = 1;
	ins6(tc_to_f, to_dph, inc_tc, acc_t, reg_sph, nop); // 29-10-2024 change acc_a to acc_t
	no_f_write_error = 0;
	
	ins6(nop, to_pch, ld, acc_t, ext, nop);  // to_pch <- (dph|dpl), pcl <- T . To move down later.

	// F=0 no cy occurred		  F=1 cy occurred

	ins6(nop, to_t, inc, acc_a, dpl, nop);	// dpl + 1 to t  3-12 upd_f

	// store T back in stackpt spl
	if_f_t(in_f(tc_to_f, to_mem, ld, acc_t, reg_spl, nop),   // if false, store T back in stackpt, tc to f. 		
		in_t(h_to_f, to_mem, ld, acc_t, reg_spl, nop)); // if true, store T back in stackpt 

	// F=0 no cy occurred		  F=1 cy occurred

	if_f_t(in_f(next_m, nop, nop, nop, nop, nop),   // if false, get next instruction
		in_t(nop, to_t, ld, acc_t, lit0, nop)); // if true, NOP

	if_f_t(in_f(irq_to_f, to_t, ld, acc_t, lit0, nop),   // if false, NOP  3-12 upd_f
		in_t(nop, to_t, inc, acc_t, reg_sph, nop)); // if true,  T <- inc(sph)

	// if stack crossed page, two cycles more:
	final(irq_to_f, to_mem, ld, acc_t, reg_sph, nop); //  store T to SPH  3-12 upd_f

	print_cycles();
}


// The function z80_ins16 generates a 16-bit data instruction. If an operand is HL, the same instruction
// will be generated for IX and IY.

function z80_ins16(opc, name, operation, dst, src, upd)  // might generate also ix/iy instructions
{
	z80_gen16(page_z80, opc, name, operation, dst, src, upd);  // basic operation

	if ((src == pair_hl) && (dst == pair_hl)) {
		z80_gen16(page_z80_ix, opc, name, operation, pair_ix, pair_ix, upd);
		z80_gen16(page_z80_iy, opc, name, operation, pair_iy, pair_iy, upd);
	}
	else if (dst == pair_hl) {
		z80_gen16(page_z80_ix, opc, name, operation, pair_ix, src, upd);
		z80_gen16(page_z80_iy, opc, name, operation, pair_iy, src, upd);
	}
	else if (src == pair_hl)  // only used for ex (sp),ix
	{
		z80_gen16(page_z80_ix, opc, name, operation, dst, pair_ix, upd);
		z80_gen16(page_z80_iy, opc, name, operation, dst, pair_iy, upd);
	}
}

// Z80 jump, call, return

function z80_jmp(page, op, name, condition, polarity) 		// JMP  jump
{
	z80_opcode(page, op, name, abs, nop); // 6-6-2023

	if (condition == flag_v)  // special action for testing overflow flag,
	{
		/*
		  The JP PE/PO of the Z80 are similar to the BVS/BVC of the 6502.

		  JP to one of the instructions 0x02, 0x03, 0x12, 0x13, 0x42, 0x43, 0x52, 0x53
		  One of the eight instructions is chosen by 3 bits from the ALU: N, A7, B7
		  Two of these instructions will deliver V=1 (in flag F), the
		  others deliver V=0 (in flag F).
		  After one of these eight instructions, a final BFS (0x14) or BFC (0x04) will
		  be done that does the actual branch.

			  - to_t <- shl_1(8+32)  // 0x50 + 1
			  - to_t <- and(acc_t,reg_v); // AND flag
			  - to_dpl <- add(acc_t,2);   // 0x02, 0x03, 0x12, 0x13, 0x42, 0x43, 0x52, 0x53 

			 - to_t <- ld_ir(acc_t,dpl);  // T unused, jp to V-flag table
			 - to_dpl <- 0x04, 0x14, 0x0B  for bvc, bvs, php 

		   20-5-2023 changed bits in reg_v to bit5, bit4, bit0
		   JP to one of the instructions 0x02, 0x03, 0x12, 0x13, 0x22, 0x23, 0x32, 0x33
		   Also have to change it for 6502
		*/	

		ins6(nop, to_t, asl, acc_t, lit16, nop);		// get bit5 (32)
		ins6(nop, to_t, add_1, acc_t, lit16, nop);	// add bit5 and 1 to get 00110001 mask

		ins6(nop, to_t, and, acc_t, reg_v, nop);    // AND with reg_v		  
		ins6(nop, to_dpl, add_1, acc_t, lit1, nop);	 // ADD 2 and move to dpl
		ins6(nop, to_t, ld_ir, acc_t, dpl, page_z80_ed);	 // load Instruction register with dpl instruction
	
		if (polarity == true) { ins6(nop, to_dpl, ld, acc_t, lit20, nop); } // 1-12 upd_f, 0x14 BFS
		else { ins6(nop, to_dpl, ld, acc_t, lit4, nop); } // 1-12 upd_f, 0x04 BFC		  

		dis_data_bytes[(current_page << 8) + current_opcode] += 2; // nr of bytes in instruction
		
		no_f_is_irq_error = 1; // 3-12 allow that F is not IRQ	  
		print_cycles(); // cycles of V0x02 (or similar) and BFS/BFC must be added to this
		return;
	}

	if (condition == z_to_f) {		
		ins6(nop, to_t, dec, acc_a, reg_z, nop);  // get z register and add 0xFF to it 3=12 upd_f
		// tc is set when reg_z was non-zero		
		condition = dtc_to_f; // 30-6-2024 check interrupt
		if (polarity == true)  // toggle polarity
			polarity = false;
		else polarity = true;
	}

	if (condition == nop)  // 3-12  for JP F, JP non-F
	  {   } 

   	// 30-6-2024 check interrupt
	if (condition != nop)
	  {	ins6_chi(nop, to_t, ld, acc_a, pc_pp, nop); // get low addr to t (was dph)
		ins6_pcmin1 (condition, to_dpl, ld, acc_a, pc_pp, nop); // get high addr to dpl	
	  } 
	else // use this for jp F, jp non-F  (no interrupt check)
	  {	ins6(nop, to_t, ld, acc_a, pc_pp, nop); // get low addr to t (was dph)
		ins6(condition, to_dpl, ld, acc_a, pc_pp, nop); // get high addr to dpl	
	  } 	
	// 10-11-2023
	if (polarity == true) { // when jp should occur if flag is true:
		if_f_t(in_f(next_m, nop, nop, nop, nop, nop), in_t(nop, to_pch, xor, acc_t, lit0, nop)); // mov t to pch
		if_f_t(in_f(delay_m, nop, nop, nop, nop, nop), in_t(nop, to_pch, ld, acc_t, dpl, nop));   //  pcl <- pch, pch <- dpl
	}
	else { // when jp should occur if flag is false:
		if_f_t(in_f(nop, to_pch, xor, acc_t, lit0, nop), in_t(next_m, nop, nop, nop, nop, nop)); // mov t to pch
		if_f_t(in_f(nop, to_pch, ld, acc_t, dpl, nop), in_t(delay_m, nop, nop, nop, nop, nop)); //  pcl <- pch, pch <- dpl
	}
	ins6(next_m, nop, nop, nop, nop, nop);		// 10-11
	ins6(delay_m, nop, nop, nop, nop, nop);
	print_cycles();
}

function ins_vcalc_z80(opc, name, val) { //opcode(op, name, nop);
	z80_opcode(page_z80_ed, opc, name, nop, nop);

	// jp to final instruction (BFC/BFS, opcode of final instruction in dph.
	// if val=true, set F. Else, clear F
	// The flag setting can not be in the delay instruction.

	if (val) {
		ins6(h_to_f, to_t, ld_ir, acc_t, dpl, page_z80_ed);  // F <- 1 and load IR
		}
	else ins6(l_to_f, to_t, ld_ir, acc_t, dpl, page_z80_ed);  // F <- 0 and load IR

	ins6(nop, to_t, ld, acc_t, reg_128, nop); // 20-7 nop in delay

	no_print_cycles_upd_f_error = 1; // 3-12
	no_f_is_irq_error = 1; // allow that F is not IRQ	  
	print_cycles();
}

// 4-11-2023 new CALL. The code is faster if SP does not cross a page.
function z80_call(op, name, condition, polarity) 		// CALL   subroutine.
{
	opcode(op, name, abs);
	// new 5-7-2023
	if (condition == z_to_f) {
		
		ins6(nop, to_t, dec, acc_a, reg_z, nop);  // get z register and add 0xFF to it 3-12 upd_f
		// tc is set when reg_z was non-zero
		// 30-6  condition = tc_to_f;
		condition = dtc_to_f; // 30-6-2024
		if (polarity == true)  // toggle polarity
			polarity = false;
		else polarity = true;
	}
	// end new
	// 30-6-2024 test irq
	ins6_chi(nop, to_dpl, ld, acc_a, pc_pp, nop); // 13-11 get low dst addr to dpl, inc pc
	ins6_pcmin1(condition, to_t, ld, acc_a, pc_pp, nop); 	// get high dst addr to T, inc pc

	if (polarity == true) { // when call should occur if flag is true:
		// 13-11
		if_f_t(in_f(next_m, nop, nop, nop, nop, nop), in_t(nop, to_t, ld_ir, acc_t, lit4, page_z80_ix)); // jump to CALR  (call-routine)
		if_f_t(in_f(delay_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_th, nop)); // 	save in temp reg_th			  
	}
	else { // when call should occur if flag is false:
		// 13-11
		if_f_t(in_f(nop, to_t, ld_ir, acc_t, lit4, page_z80_ix), in_t(next_m, nop, nop, nop, nop, nop)); // jump to CALR  (call-routine)
		if_f_t(in_f(nop, to_mem, ld, acc_t, reg_th, nop), in_t(delay_m, nop, nop, nop, nop, nop)); // save in temp reg_th
	}
	no_print_cycles_upd_f_error = 1; // 3-12
	no_f_is_irq_error = 1; // suppress error
	print_cycles();
}


// 8-11-2023 new function. Code for CALL is too long, it is continued here as CALR (call-routine)
function z80_calr(page, opc, name) {
	z80_opcode(page, opc, name, nop, nop); 	// instruction 04 in IX group

	// 11-1-2025  add debugging
    ins6(nop,to_t,asl,acc_t,reg_dbg,nop);  // check debug register
	ins6(tc_to_f, to_t, ld, acc_t, pcl, nop);  // get pcl move it to t, tc_to_f

    //       F=0    normal                                    F=1  jump to debug. Target addr of call in dpl(lsb) and reg_th(msb)
	if_f_t(in_f(nop, to_pch, ld, acc_t, dpl, nop),    in_t(nop, to_t, ld_ir, acc_t, lit32, page_z80_iy)); // F0: pch<-target_low (from dpl)  F1: jp to 0x20 in page_z80_iy
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_tl, nop), in_t(delay_m, nop, nop, nop, nop, nop)); // F0: store pcl (re-use reg_tl)  F1: delay

    // debug checking needes one extra cycle for calls.
    // 11-1-2025 end

	ins6(nop, to_t, ld, acc_t, pcl, nop); // t <- pcl (this is actuall pc-msb)
	
	//13-11 new, load SP:
	ins6(nop, to_dpl, dec, acc_a, reg_spl, nop);   // load spl
	ins6(nop, to_dph, dec_tc, acc_t, reg_sph, nop); // load sph  3-12 upd_f

	ins6(dtc_to_f, to_mem, ld, acc_t, ext, nop);	// 13-11 store pc-msb to stack

	// F=0 crossed page       F=1 not crossed page

	ins6(nop, to_dpl, dec, acc_t, dpl, nop);   // dec dpl  3-12 upd_f

	// 10-11-2023  get pc-lsb to T. was from pcl, now from saved reg_tl
	// no need to check condition. It is not a valid var, and no need to keep code short here.

	if_f_t(in_f(l_to_f, to_t, ld, acc_t, reg_tl, nop), // if false, pcl to T
		in_t(tc_to_f, to_t, ld, acc_t, reg_tl, nop));  // if true, pcl to T, tc_to_f

	// F=0 crossed page       F=1 not crossed page

	if_f_t(in_f(nop, to_dph, dec, acc_t, reg_sph, nop), // if false, conditional decr dph 8-11-2023 // 29-10-2024 change acc_a to acc_t
		in_t(nop, to_mem, ld, acc_t, ext, nop));  // if true, save T (LSB) to stack

	// 13-11-2023
	if_f_t(in_f(nop, to_mem, ld, acc_t, ext, nop), // if false, save T (LSB) to stack
		in_t(nop, to_pch, ld, acc_t, reg_th, nop));  // if true, load pch & pcl
	// 13-11 end

	if_f_t(in_f(nop, to_pch, ld, acc_t, reg_th, nop), // if false, load pch & pcl
		in_t(nop, to_t, ld, acc_t, dpl, nop));  // if true, dpl to T

	if_f_t(in_f(nop, to_t, ld_ir, acc_t, lit8, page_z80_ix), // if false, jp to addr 8 (store SP)  21-11-2023

		in_t(next_m, nop, nop, nop, nop, nop));   // if true, next instruction

	if_f_t(in_f(nop, to_t, dec, acc_t, reg_sph, nop), // if false, t <- dec(sph)	  8-11 new
		in_t(irq_to_f, to_mem, ld, acc_t, reg_spl, nop));   // if true,store T to SP-low 3-12 upd_f

	no_print_cycles_upd_f_error = 1; // 3-12
	no_f_is_irq_error = 1; // suppress error that occurs for call z/nz
	print_cycles();
	return;
}


function z80_stsp(page, opc, name) {
	z80_opcode(page, opc, name, nop, nop); 	// instruction 05 in IX group // 21-11-2023 now number 8

	// 8-11-2023  sph must already be in T
	ins6(nop, to_mem, ld, acc_t, reg_sph, nop);	// store T back in stackpt sph	3-12 upd_f
	ins6(irq_to_f, to_t, ld, acc_a, dpl, nop);	// dpl to t
	final(irq_to_f, to_mem, ld, acc_t, reg_spl, nop);	// store T back in stackpt spl 3-12 irq_to_f, upd_f

	print_cycles();
}


function z80_restart_addr(number)   // will put restart addr in PCH (13-11-2023)
{	// number is three bits, value 0-7
	var middle = 0;
	if (number & 0x02) { middle = 1; number = number & 0x05; } // isolate the middle bit

	if (middle) dest = to_t; else dest = to_pch;

	if (number == 0x00) { ins6(nop, dest, ld, acc_t, lit0, nop); }  // ld 0x00		for 0x00
	if (number == 0x01) { ins6(nop, dest, asl, acc_t, lit4, nop); }  // ld shl(4)  for 0x08
	if (number == 0x04) { ins6(nop, dest, asl, acc_t, lit16, nop); }  // ld shl(16) for 0x20
	if (number == 0x05) { ins6(nop, dest, asl, acc_t, lit20, nop); }  // ld shl(20) for 0x28

	if (middle) { ins6(nop, to_pch, or, acc_t, lit16, nop); } // or 16 (0x10)
}


// 13-11 new:
function z80_restart(op, name, number) 		// RST  jump to subroutine.
{
	opcode(op, name, nop);
	// 30-6-2024 check irq
	ins6_chi(nop, to_t, ld, acc_t, pcl, nop);		// 13-11 get pcl move it to t, no dtc_to_f
	ins6_pcmin1(nop, to_mem, ld, acc_t, reg_tl, nop); // store pcl 	

	z80_restart_addr(number); // 13-11 low byte of target addr to PCH	

	ins6(nop, to_t, ld, acc_t, pcl, nop); // t <- pcl (this is actuall pc-msb)
	// end new

	//13-11 new, load SP:
	ins6(nop, to_dpl, dec, acc_a, reg_spl, nop);   // load spl
	ins6(nop, to_dph, dec_tc, acc_t, reg_sph, nop); // load sph  3-12 upd_f

	ins6(dtc_to_f, to_mem, ld, acc_t, ext, nop);	// 13-11 store pc-msb to stack

	// F=0 crossed page       F=1 not crossed page

	ins6(nop, to_dpl, dec, acc_t, dpl, nop);   // dec dpl  3-12 upd_f

	// 10-11-2023  get pc-lsb to T. was from pcl, now from saved reg_tl
	// no need to check condition. It is not a valid var, and no need to keep code short here.

	if_f_t(in_f(l_to_f, to_t, ld, acc_t, reg_tl, nop), // if false, pcl to T
		in_t(tc_to_f, to_t, ld, acc_t, reg_tl, nop));  // if true, pcl to T, tc_to_f

	// F=0 crossed page       F=1 not crossed page

	if_f_t(in_f(nop, to_dph, dec, acc_t, reg_sph, nop), // if false, conditional decr dph 8-11-2023 // 29-10-2024 change acc_a to acc_t
		in_t(nop, to_mem, ld, acc_t, ext, nop));  // if true, save T (LSB) to stack

	// 13-11-2023
	if_f_t(in_f(nop, to_mem, ld, acc_t, ext, nop), // if false, save T (LSB) to stack	   	      
		in_t(nop, to_pch, ld, acc_t, lit0, nop));  // 13-11 if true, load pch & pcl
	// 13-11 end

	if_f_t(in_f(nop, to_pch, ld, acc_t, lit0, nop), // 13-11 if false, load pch & pcl	  
		in_t(nop, to_t, ld, acc_t, dpl, nop));  // if true, dpl to T

	if_f_t(in_f(nop, to_t, ld_ir, acc_t, lit8, page_z80_ix), // if false, jp to addr 8 (store SP)  21-11-2023
		in_t(next_m, nop, nop, nop, nop, nop));   // if true, next instruction

	if_f_t(in_f(nop, to_t, dec, acc_t, reg_sph, nop), // if false, t <- dec(sph)	  8-11 new
		in_t(irq_to_f, to_mem, ld, acc_t, reg_spl, nop));   // if true,store T to SP-low 3-12 upd_f

	// todo: both NOP's could be eliminated, shortening the code.
	no_print_cycles_upd_f_error = 1; // 3-12
	no_f_is_irq_error = 1; // suppress error
	print_cycles();
}

// 11-1-2025 new. DBGC  debug-call. When debugging is active, a CALL instruction will execute this.
function z80_dbgc(page, opc, name) {
	z80_opcode(page, opc, name, nop, nop); 	// instruction 0x20 in IY group 
    // the address after the 3 bytes of the CALL instruction is written to reg_th/reg_tl
	// In the first instruction of the debugger, th/tl can be saved to memory with an ED 7F instruction
	ins6(nop, to_t, ld, acc_a, pcl, nop);	// pcl to t
    ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // reg_tl <- t  PC lsb
	ins6(nop, to_pch, ld, acc_a, lit32, nop);	 // pch <- 0x20  lsb of debug routine, for CALL
	ins6(nop, to_t, ld, acc_a, pcl, nop);	// pch to t
    ins6(nop, to_mem, ld, acc_t, reg_th, nop); // reg_th <- t  PC msb
    // complete the jmp address to debug routine
	ins6(nop, to_pch, ld, acc_a, reg_dbg, nop);	// pch <- msb of debug routine
	// jump to the debug routine. Set F to 1 (h_to_f), because no interrupt allowed. An 
	// interrupt could overwrite the th/tl registers	

	ins6(h_to_f, to_t, ld_ir, acc_a, pc_pp, page_z80);	//  (first instruction of debugger at XX28 ) 9-2-2025 use Z80 page !

	ins6(nop, to_t, ld, acc_t, lit0, nop);	// delay

	print_cycles();
}

// 11-1-2025 new. DBGR  debug-return. When debugging is active, a RET instruction will execute this.
function z80_dbgr(page, opc, name) {
	z80_opcode(page, opc, name, nop, nop); 	// instruction 0x28 in IY group 
    // the address after that where the RET instruction was found, is written to reg_th/reg_tl
	// In the first instruction of the debugger, th/tl can be saved to memory with an ED 7F instruction
	ins6(nop, to_t, ld, acc_a, pcl, nop);	// pcl to t
    ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // reg_tl <- t  PC lsb
	ins6(nop, to_pch, ld, acc_a, lit40, nop);	 // pch <- 0x28  lsb of debug routine, for RET
	ins6(nop, to_t, ld, acc_a, pcl, nop);	// pch to t
    ins6(nop, to_mem, ld, acc_t, reg_th, nop); // reg_th <- t  PC msb
    // complete the jmp address to debug routine
	ins6(nop, to_pch, ld, acc_a, reg_dbg, nop);	// pch <- msb of debug routine
	// jump to the debug routine. Set F to 1 (h_to_f), because no interrupt allowed. An 
	// interrupt could overwrite the th/tl registers

	ins6(h_to_f, to_t, ld_ir, acc_a, pc_pp, page_z80);	//  (first instruction of debugger at XX28 ) 9-2-2025 use Z80 page !

	ins6(nop, to_t, ld, acc_t, lit0, nop);	// delay

	print_cycles();
}


// 9-11-2023 New
function z80_ret(op, name, condition, polarity) 		// RET  return from subroutine
{
	opcode(op, name, nop);

	if (condition == z_to_f) {		
		ins6(nop, to_t, dec, acc_a, reg_z, nop);  // get z register and add 0xFF to it 3-12 upd_f
		// tc is set when reg_z was non-zero		
		condition = dtc_to_f; // 30-6-2024
		if (polarity == true)  // toggle polarity
			polarity = false;
		else polarity = true;
	}
	ins6_chi(nop, to_dpl, ld, acc_a, reg_spl, nop); // get low addr sp to dpl
	ins6_pcmin1(condition, to_dph, ld, acc_t, reg_sph, nop); // get high addr sp to dph // 29-10-2024 change acc_a to acc_t

	// 11-1-2025  debugging added
	{	if (polarity == true) { // when return should occur if flag is true:
			if_f_t(in_f(next_m, nop, nop, nop, nop, nop), in_t(nop, to_t, asl, acc_t, reg_dbg, nop)); // check debug register bit 7
			if_f_t(in_f(delay_m, nop, nop, nop, nop, nop), in_t(tc_to_f,to_t,ld,acc_t,lit0,nop)); // nop, tc_to_f
		}
		else { // when return should occur if flag is false:
			if_f_t(in_f(nop, to_t, asl, acc_t, reg_dbg, nop), in_t(next_m, nop, nop, nop, nop, nop)); // check debug register
			if_f_t(in_f(tc_to_f,to_t,ld,acc_t,lit0,nop), in_t(delay_m, nop, nop, nop, nop, nop)); //
		}
	}
    //       F=0    normal                                    F=1  jump to debug
	if_f_t(in_f(nop, to_pch, ld, acc_t, ext, nop),      in_t(nop, to_t, ld_ir, acc_t, lit40, page_z80_iy)); // jp to DBGR, instr 0x28 in IY page
	if_f_t(in_f(nop, to_dpl, inc, acc_a, reg_spl, nop), in_t(delay_m, nop, nop, nop, nop, nop)); //
    // checking debug costs two cycles
	// 11-1-2025 end

	// 9-11-2023
	no_f_write_error = 1;
	ins6(tc_to_f, to_dph, inc_tc, acc_t, reg_sph, nop); // 29-10-2024 change acc_a to acc_t
	no_f_write_error = 0;
	
	ins6(nop, to_pch, ld, acc_t, ext, nop);  // to_pch <- (dph|dpl), pcl <- T . To move down later.

	// F=0 no cy occurred		  F=1 cy occurred

	ins6(nop, to_t, inc, acc_a, dpl, nop);	// dpl + 1 to t  3-12 upd_f

	// store T back in stackpt spl
	if_f_t(in_f(tc_to_f, to_mem, ld, acc_t, reg_spl, nop),   // if false, store T back in stackpt, tc to f. 		
		in_t(h_to_f, to_mem, ld, acc_t, reg_spl, nop)); // if true, store T back in stackpt 

	// F=0 no cy occurred		  F=1 cy occurred

	if_f_t(in_f(next_m, nop, nop, nop, nop, nop),   // if false, get next instruction
		in_t(nop, to_t, ld, acc_t, lit0, nop)); // if true, NOP

	if_f_t(in_f(irq_to_f, to_t, ld, acc_t, lit0, nop),   // if false, NOP  3-12 upd_f
		in_t(nop, to_t, inc, acc_t, reg_sph, nop)); // if true,  T <- inc(sph)

	// if stack crossed page, two cycles more:
	final(irq_to_f, to_mem, ld, acc_t, reg_sph, nop); //  store T to SPH  3-12 upd_f

	print_cycles();

}


// rotate-right-digit
// How do we do that ?
//   First we swap the lower nibbles between A and (HL)
//   Then we swap both nibbles of (HL) by using a nibble-swap table
//   The nibble-swap table must be filled by the application.
// How do we swap lower nibbles between A and (HL) ?
// First we calculate the difference between those bytes with a XOR instruction.
// We then clear the upper 4 bits of that difference.
// Then we apply the difference to both A and (HL) with an XOR instruction.
//
// RRD is used in The Great Escape (ZX Spectrum)

function z80_rrd(page, opc, name)			// RRD   Rotate-Right-Digit ED 67  23-6-2024
{   z80_opcode(page, opc, name, nop, nop);
	ins6_chi(nop, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6_pcmin2(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register	
	ins6(nop, to_t, xor, acc_a, ext, nop); // T <- A xor (hl)

	// reset upper 4 bits of T, result in dpl
	ins6(nop, to_t, and, acc_t, reg_0F, nop); // T <- T and 0x0F. reg_0F initialized in launch.

	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // reg_tl <- T
	ins6(nop, to_a, xor, acc_a, reg_tl, nop); // A <- A xor reg_tl

	ins6(nop, to_dpl, xor, acc_t, ext, nop); // dpl <- T xor (hl)
	ins6(nop, to_dph, inc, acc_t, lit1, nop); // MSB of nibble swap table (0200 -02FF) in bank2

	ins6(nop, to_t, ld, acc_a, ext, bank2);  // T <- swaptable(dph|dpl), bank2
	ins6(irq_to_f, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register

	final(nop, to_mem, ld, acc_t, ext, nop); // (HL) <- T		

	print_cycles();  // 13 + 2 cycles  (Z80: 11)
}

// RLD is the same as RRD, but here we first swap both (HL) halves, and then 
// the lower nibbles between A and (HL)
// Not yet tested.

function z80_rld(page, opc, name)			// RLD   Rotate-Left-Digit ED 6F  23-6-2024
{   z80_opcode(page, opc, name, nop, nop);
	ins6_chi(nop, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6_pcmin2(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register	
	ins6(nop, to_dpl, ld, acc_t, ext, nop);   // dpl <- (hl)
	ins6(nop, to_dph, inc, acc_t, lit1, nop); // MSB of nibble swap table (0200 -02FF) in bank2
    // now dph/dpl points to the nibble-swapped (HL)

	ins6(nop, to_t, xor, acc_a, ext, bank2); // T <- A xor swaptable(dph|dpl), bank2
	// reset upper 4 bits of T, result in dpl
	ins6(nop, to_t, and, acc_t, reg_0F, nop); // T <- T and 0x0F. reg_0F initialized in launch.

	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // reg_tl <- T
	ins6(nop, to_a, xor, acc_a, reg_tl, nop); // A <- A xor reg_tl

	ins6(nop, to_t, ld, acc_t, ext, nop); // T <- T xor swaptable(dph|dpl), bank2

	ins6(irq_to_f, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register

	final(nop, to_mem, ld, acc_t, ext, nop); // (HL) <- T		

	print_cycles();  // 13 + 2 cycles  (Z80: 11)
}


function z80_ldi(page, opc, name)			// LDI   Load-increment ED A0  22-6-2024
{   z80_opcode(page, opc, name, nop, nop);
	ins6_chi(nop, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6_pcmin2(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register	
	ins6(nop, to_t, ld, acc_t, ext, nop); // get data from (hl)

	ins6(nop, to_dph, ld, acc_t, reg_d, nop);	// d register	
	ins6(nop, to_dpl, ld, acc_t, reg_e, nop);	// e register	
	ins6(nop, to_mem, ld, acc_t, ext, nop); // store data at (de)

    // now inc HL. 
	ins6(nop, to_t, inc, acc_t, reg_l, nop); // 
	ins6(nop, to_mem, ld, acc_t, reg_l, nop); // store incremented L register

	ins6(nop, to_t, inc_dtc, acc_t, reg_h, nop); // increment H if there was cy
	ins6(nop, to_mem, ld, acc_t, reg_h, nop); // store incremented H register

    // now inc DE. 
	ins6(nop, to_t, inc, acc_t, reg_e, nop); // 
	ins6(irq_to_f, to_mem, ld, acc_t, reg_e, nop); // store incremented E register

	ins6(nop, to_t, inc_dtc, acc_t, reg_d, nop); // increment D if there was cy

	// 6-3-2025
	ins6(nop, to_dpl, asl, acc_t, lit32, nop); 	// 0x40 to dpl
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_z80_ix);   // jp to new DEC BC
	ins6(nop, to_mem, ld, acc_t, reg_d, nop); // store incremented D register

	print_cycles();  // 15 + 2 cycles  (Z80: 16)
}

function z80_ldd(page, opc, name)			// LDD   Load-decrement ED A8  30-6-2024
{   z80_opcode(page, opc, name, nop, nop);
	ins6_chi(nop, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6_pcmin2(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register	
	ins6(nop, to_t, ld, acc_t, ext, nop); // get data from (hl)

	ins6(nop, to_dph, ld, acc_t, reg_d, nop);	// d register	
	ins6(nop, to_dpl, ld, acc_t, reg_e, nop);	// e register	
	ins6(nop, to_mem, ld, acc_t, ext, nop); // store data at (de)

    // now dec HL. 
	ins6(nop, to_t, dec, acc_t, reg_l, nop); // 
	ins6(nop, to_mem, ld, acc_t, reg_l, nop); // store decremented L register

	ins6(nop, to_t, dec_dtc, acc_t, reg_h, nop); // decrement H if there was cy
	ins6(nop, to_mem, ld, acc_t, reg_h, nop); // store decremented H register

    // now dec DE. 
	ins6(nop, to_t, dec, acc_t, reg_e, nop); // 
	ins6(irq_to_f, to_mem, ld, acc_t, reg_e, nop); // store decremented E register

	ins6(nop, to_t, dec_dtc, acc_t, reg_d, nop); // decrement D if there was cy
	
	// 6-3-2025
	ins6(nop, to_dpl, asl, acc_t, lit32, nop); 	// 0x40 to dpl
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_z80_ix);   // jp to new DEC BC
	ins6(nop, to_mem, ld, acc_t, reg_d, nop); // store decremented D register	

	print_cycles();  // 15 + 2 cycles  (Z80: 16)
}


function z80_cpi(page, opc, name)			// CPI   compare-increment ED A1  16-9-2024
{   z80_opcode(page, opc, name, nop, nop);
	ins6_chi(nop, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6_pcmin2(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register	
	ins6(nop, to_t, sub, acc_a, ext, upd_n); // calculate A - (hl), update N flag

	ins6(nop, to_mem, ld, acc_t, reg_z, nop); // result to reg_z  ( Z flag)  10-3-2025
	// now dec BC
	ins6(nop, to_t, dec, acc_t, reg_c, nop);		   // T <- reg_c -1
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);          // reg_c <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_b, nop);       // T reg_b - 1 (if there was a cy)
	ins6(nop, to_mem, ld, acc_t, reg_b, nop);     // delay, reg_b <- T
    // now inc HL. 
	ins6(nop, to_t, inc, acc_t, reg_l, nop); // 
	ins6(irq_to_f, to_mem, ld, acc_t, reg_l, nop); // store incremented L register
	ins6(nop, to_t, inc_dtc, acc_t, reg_h, nop); // increment H if there was cy	
	final(nop, to_mem, ld, acc_t, reg_h, nop); // store incremented H register
	
 	print_cycles();  // 13 + 2 cycles  (Z80: 16)
}

function z80_cpd(page, opc, name)			// CPD   compare-decrement ED A9  16-9-2024
{   z80_opcode(page, opc, name, nop, nop);
	ins6_chi(nop, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6_pcmin2(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register	
	ins6(nop, to_t, sub, acc_a, ext, upd_n); // calculate A - (hl), update N flag

	ins6(nop, to_mem, ld, acc_t, reg_z, nop); // result to reg_z  ( Z flag)  10-3-2025
	// now dec BC
	ins6(nop, to_t, dec, acc_t, reg_c, nop);		   // T <- reg_c -1
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);          // reg_c <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_b, nop);       // T reg_b - 1 (if there was a cy)
	ins6(nop, to_mem, ld, acc_t, reg_b, nop);     // delay, reg_b <- T
    // now dec HL. 
	ins6(nop, to_t, dec, acc_t, reg_l, nop); // 
	ins6(irq_to_f, to_mem, ld, acc_t, reg_l, nop); // store decremented L register
	ins6(nop, to_t, dec_dtc, acc_t, reg_h, nop); // decrement H if there was cy	
	final(nop, to_mem, ld, acc_t, reg_h, nop); // store decremented H register

 	print_cycles();  // 13 + 2 cycles  (Z80: 16)
}

// The CPIR and CPDR take more than 16 cycles, so they also occupy the space of the next instruction.
// But those next instructions are INIR and INDR that will probably never get implemented.... 

function z80_cpir(page, opc, name)			// CPIR   compare-increment-repeat ED B1  17-9-2024
{   z80_opcode(page, opc, name, nop, nop);
	ins6_chi(nop, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6_pcmin2(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register	
	ins6(nop, to_t, sub, acc_a, ext, upd_n); // calculate A - (hl), update N flag

	// 10-3-2025  ins6(nop, to_mem, dec, acc_t, reg_z, nop); // result to reg_z  ( Z flag)
	ins6(nop, to_mem, ld, acc_t, reg_z, nop); // result to reg_z  ( Z flag)  10-3-2025

	// now dec BC
	ins6(nop, to_t, dec, acc_t, reg_c, nop);		   // T <- reg_c -1
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);          // reg_c <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_b, nop);       // T reg_b - 1 (if there was a cy)
	ins6(nop, to_mem, ld, acc_t, reg_b, nop);     // delay, reg_b <- T
	
    // now inc HL. 
	ins6(nop, to_t, inc, acc_t, reg_l, nop); // 
	ins6(irq_to_f, to_mem, ld, acc_t, reg_l, nop); // store incremented L register
	ins6(nop, to_t, inc_dtc, acc_t, reg_h, nop); // increment H if there was cy	
	ins6(nop, to_mem, ld, acc_t, reg_h, nop); // store incremented H register

	// now, stop if A = (HL), or if BC = 0.

	ins6(nop, to_t, dec, acc_a, reg_z, nop);  // get z register and add 0xFF 
    ins6(tc_to_f, to_t, ld, acc_a, reg_b, nop);  // get reg B, F <- TC
	// tc is set when reg_z was non-zero
    //F=0  zero-result, stop         F=1 continue
	if_f_t(in_f(next_m,nop,nop,nop,nop,nop),in_t(nop, to_t, or, acc_t, reg_c, nop) ); //   F=1: T <- T or reg_c
	if_f_t(in_f(delay_m,nop,nop,nop,nop,nop),in_t(nop, to_t, sub_0, acc_t, lit0, nop) ); // F=1: T <- sub_0(T , lit0)  // add 0xFF

	ins6(tc_to_f, to_t, ld, acc_a, lit0, nop);  // F <- TC, nop
	// tc is set when BC was non-zero

	if_f_t(in_f(next_m,nop,nop,nop,nop,nop),in_t(nop, to_t, ld, acc_t, pcl, nop) ); //   F=1: T <- pcl	10-3-2025
	if_f_t(in_f(delay_m,nop,nop,nop,nop,nop),in_t(nop, to_pch, sub_0, acc_t, lit1, nop) ); // F=1: pch <- sub_0(T , lit1)  // add 0xFF
	
	ins6(nop, to_pch, dec_tc, acc_t, pcl, nop);	
	final(irq_to_f, to_t, ld, acc_t, lit0, nop); // PC was decremented by 2. Repeat same instruction.

 	print_cycles();  // 22 + 2 cycles  (Z80: 16)
}

function z80_cpdr(page, opc, name)			// CPDR   compare-decrement-repeat ED B9  17-9-2024
{   z80_opcode(page, opc, name, nop, nop);
	ins6_chi(nop, to_dph, ld, acc_t, reg_h, nop);	// h register	
	ins6_pcmin2(nop, to_dpl, ld, acc_t, reg_l, nop);	// l register	
	ins6(nop, to_t, sub, acc_a, ext, upd_n); // calculate A - (hl), update N flag

	// 10-3-2025  ins6(nop, to_mem, dec, acc_t, reg_z, nop); // result to reg_z  ( Z flag)
	ins6(nop, to_mem, ld, acc_t, reg_z, nop); // result to reg_z  ( Z flag)  10-3-2025

	// now dec BC
	ins6(nop, to_t, dec, acc_t, reg_c, nop);		// T <- reg_c -1
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);       // reg_c <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_b, nop);    // T reg_b - 1 (if there was a cy)
	ins6(nop, to_mem, ld, acc_t, reg_b, nop);     	// delay, reg_b <- T
	
    // now dec HL. 
	ins6(nop, to_t, dec, acc_t, reg_l, nop); // 
	ins6(nop, to_mem, ld, acc_t, reg_l, nop); // store decremented L register
	ins6(nop, to_t, dec_dtc, acc_t, reg_h, nop); // decrement H if there was cy	
	ins6(nop, to_mem, ld, acc_t, reg_h, nop); // store incremented H register

	// now, stop if A = (HL), or if BC = 0.	

	ins6(nop, to_t, dec, acc_a, reg_z, nop);  // get z register and add 0xFF 
    ins6(tc_to_f, to_t, ld, acc_a, reg_b, nop);  // get reg B, F <- TC
	// tc is set when reg_z was non-zero
    //F=0  zero-result, stop         F=1 continue
	if_f_t(in_f(next_m,nop,nop,nop,nop,nop),in_t(nop, to_t, or, acc_t, reg_c, nop) ); //   F=1: T <- T or reg_c
	if_f_t(in_f(delay_m,nop,nop,nop,nop,nop),in_t(nop, to_t, sub_0, acc_t, lit0, nop) ); // F=1: T <- sub_0(T , lit0)  // add 0xFF

	ins6(tc_to_f, to_t, ld, acc_a, lit0, nop);  // F <- TC, nop
	// tc is set when BC was non-zero
	
	if_f_t(in_f(next_m,nop,nop,nop,nop,nop),in_t(nop, to_t, ld, acc_t, pcl, nop) ); //   F=1: T <- pcl	10-3-2025
	if_f_t(in_f(delay_m,nop,nop,nop,nop,nop),in_t(nop, to_pch, sub_0, acc_t, lit1, nop) ); // F=1: pch <- sub_0(T , lit1)  // add 0xFF

	ins6(nop, to_pch, dec_tc, acc_t, pcl, nop);	
	final(irq_to_f, to_t, ld, acc_t, lit0, nop); // PC was decremented by 2. Repeat same instruction.

 	print_cycles();  // 22 + 2 cycles  (Z80: 16)
}


// 14-9-2024 new LDIR functions

function z80_ldir_prep(page, opc, name)			// LDIR   Load-increment-repeat prepare  ED 06
{
	z80_opcode(page, opc, name, nop, nop);

	// first 2 instructions also check for interrupt and handle that
	ins6_chi(nop, to_mem, ld, acc_a, reg_v, nop); // save A in reg_v
	// pc to reg_tl, reg_th
	ins6_pcmin2(nop, to_t, ld, acc_t, pcl, nop);    
	ins6(nop, to_mem, ld, acc_t, reg_tl, nop);
	ins6(nop, to_pch, ld, acc_t, reg_l, nop);   //
	ins6(nop, to_t, ld, acc_t, pcl, nop);		//
	ins6(nop, to_mem, ld, acc_t, reg_th, nop);
	ins6(nop, to_pch, ld, acc_t, reg_h, nop);
    //  PC has been saved, and HL has been moved to PC

	// create the opcode of LDIR_LOOP, 0x98
	ins6(nop, to_t, asl, acc_t, lit8, nop); // value 0x10
	ins6(nop, to_t, or, acc_t, lit8, nop);  // T <_ T OR 8, gives 0x18
	ins6(nop, to_t, or, acc_t, reg_128, nop); // now have 0x98
	
	ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop); // save at reg_vga_acc

	// jp to loop	
	ins6(nop, to_t, ld_ir, acc_t, reg_vga_acc, page_z80_ed);	// JP to loop
	ins6(nop, to_mem, ld, acc_a, reg_v, nop);  // delay, save A in reg_v ? was already done.

	no_print_cycles_upd_f_error = 1; // 3-12
	no_f_is_irq_error = 1; // 3-12 suppress error	
	print_cycles(); // 13 cycles
}


// The LDIR_LOOP will take more than 32 cycles, so reserve 3 opcode positions for this.

function z80_ldir_loop(page, opc, name)     // loop at 0x98  copy from (pc++) to (DE++), count in BC
{
	z80_opcode(page, opc, name, nop, nop);

    // decide if we can do an unrolled loop. If not, goto slow.
	ins6(nop, to_a, ld, acc_t, reg_c, nop);  // A <- reg_c (count, LSB)
	ins6(nop, to_a, sub, acc_a, lit8, nop);  // A <- A - 8. Will clr TC if result is negative
	ins6(tc_to_f, to_t, ld, acc_t, reg_e, nop);  // T <- reg_e (dst, LSB); F <- TC
	//  F=0  goto slow (lit32) if the count was less than 8         F=1  
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, lit32, page_z80_ed),in_t(nop, to_t, add, acc_t, lit8, nop), ); // F=1 T <- T + 8
	ins6(tc_to_f, to_dpl, ld, acc_t, reg_e, nop); // DPL <- reg_e; F <- TC	
	//  F=0  we can do an unrolled loop             F=1   goto slow (lit32) if dst was > 246
	if_f_t(in_f(nop, to_dph, ld, acc_t, reg_d, nop), in_t(nop, to_t, ld_ir, acc_t, lit32, page_z80_ed)); // F=0  DPH <- reg_d

	if_f_t(in_f(nop, to_mem, ld, acc_a, reg_c, nop), in_t(nop, to_t, add, acc_t, lit0, nop)); // F=0   reg_c <- A  // count - 8  F=1 delay(nop)
	
	ins6(nop, to_mem, ld, acc_t, reg_e, nop);  // reg_e <- T  // dst + 8	
    // start unrolled copy loop
    i =0;
	while (i<8)  // 8 times
	  { ins6(nop, to_a, ld, acc_t, pc_pp, nop); // A <- (PC++)
	    if (i < 7) ins6(irq_to_f, to_mem, ld, acc_a, ext, nop); // (DPH/DPL) <- A; F <- IRQ // for 8th cycle, done in delay.
		if (i < 7) ins6(nop, to_dpl, inc, acc_t, dpl, nop); // DPL <- DPL + 1 // not needed in 8th cycle
	  i++;
	  }
	//  F=0  Interrupt active !             F=1  no interrupt, go back to loop
	if_f_t(in_f(nop, to_t, ld, acc_t, lit0, nop), in_t(nop, to_t, ld_ir, acc_t, reg_vga_acc, page_z80_ed)); // F: nop		T: goto loop
    ins6(irq_to_f, to_mem, ld, acc_a, ext, nop); // (DPH/DPL) <- A; F <- IRQ // delay slot

	// put PC.lsb back in L
	ins6(nop, to_t, ld, acc_t, pcl, nop); //  t <- pcl
	ins6(nop, to_mem, ld, acc_t, reg_l, nop);  // reg_l <- T 

    // PCL <- saved_PC - 2
	ins6(nop, to_t, ld, acc_t, reg_tl, nop); //   T <- temp_L
	ins6(nop, to_pch, sub_0, acc_t, lit1, nop); // PCH <- T -2

	// put PC.msb back in H
	ins6(nop, to_t, ld, acc_t, pcl, nop); //  t <- pcl 
	ins6(nop, to_mem, ld, acc_t, reg_h, nop);  // reg_h <- T 

	ins6(nop, to_pch, dec_dtc, acc_t, reg_th, nop); // PCL <- PCH; PCH <- temp_H (decremented depending on last SUB_0)

	// for interrupt, PC is now decremented by 2 to point to ED B0 again

	ins6(interrupt_m, nop, nop, nop, nop, nop);	// go to interrupt
	ins6(irq_to_f, to_a, ld, acc_a, reg_v, nop); // restore A 

	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1;
	print_cycles();  // 41 cycles  (inner loop is 32 cycles)
}

// ldir_slow , at lit32 (0x20)

function z80_ldir_slow(page, opc, name)     // handle incrementing B register, end, and interrupt (also end)
{
	z80_opcode(page, opc, name, nop, nop);
    // check if BC=0
	ins6(nop, to_t, ld, acc_t, reg_c, nop);	// get c register
	ins6(nop, to_dpl, or, acc_t, reg_b, nop); // or with b, check for zero count
	ins6(nop, to_dpl, dec, acc_t, dpl, nop); // add FF to check for zero, TC=0 if zero

	ins6(tc_to_f, to_dpl, ld, acc_a, reg_e, nop);  // get zero condition in F, and DPL <- reg_e
	//   F=0: BC=0,  stop copying		F=1: nonzero

	// F=0 put PC.lsb back in L
	if_f_t(in_f(nop, to_t, ld, acc_t, pcl, nop), in_t(nop, to_dph, ld, acc_t, reg_d, nop)); //  F=1   DPH <- reg_d
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_l, nop), in_t(nop, to_a, ld, acc_a, pc_pp, nop));  // F=1  A <- (PC++)

    // F=0 PCL <- saved_PC
	if_f_t(in_f(nop, to_pch, ld, acc_t, reg_tl, nop), in_t(nop, to_mem, ld, acc_a, ext, nop)); // F=1  (dph/dpl) <- A

	// F=0 put PC.msb back in H
	if_f_t(in_f(nop, to_t, ld, acc_t, pcl, nop), in_t(nop, to_t, inc, acc_t, reg_e, nop)); //  F=1  T <- reg_e + 1
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_h, nop), in_t(nop, to_mem, ld, acc_t, reg_e, nop));  // reg_e <- T 

    // F=0 PCL <- PCH; PCH <- temp_H
	if_f_t(in_f(nop, to_pch, ld, acc_t, reg_th, nop), in_t(nop, to_t, inc_dtc, acc_t, reg_d, nop)); // F=1 T <- reg_d + 1 

	// F=0  next instruction

	if_f_t(in_f(next_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_d, nop));	 // F=1 reg_d <- T
	if_f_t(in_f(irq_to_f, to_a, ld, acc_a, reg_v, nop), in_t(nop, to_t, dec, acc_t, reg_c, nop)); // F=1  T <- reg_c -1

    // only F=1 left.
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);          // reg_c <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_b, nop);       // T reg_b - 1 (if there was a cy)
	ins6(irq_to_f, to_mem, ld, acc_t, reg_b, nop);     // reg_b <- T

    //one byte copied.

	//  F=0  Interrupt active !             F=1  no interrupt, go back to loop
	if_f_t(in_f(nop, to_t, ld, acc_t, lit0, nop), in_t(nop, to_t, ld_ir, acc_t, reg_vga_acc, page_z80_ed)); // F: nop		T: goto loop

	// put PC.lsb back in L
	ins6(nop, to_t, ld, acc_t, pcl, nop); //  t <- pcl ; also delay slot
	ins6(nop, to_mem, ld, acc_t, reg_l, nop);  // reg_l <- T 

    // PCL <- saved_PC - 2
	ins6(nop, to_t, ld, acc_t, reg_tl, nop); //   T <- temp_L
	ins6(nop, to_pch, sub_0, acc_t, lit1, nop); // PCH <- T -2

	// put PC.msb back in H
	ins6(nop, to_t, ld, acc_t, pcl, nop); //  t <- pcl 
	ins6(nop, to_mem, ld, acc_t, reg_h, nop);  // reg_h <- T 

	ins6(nop, to_pch, dec_dtc, acc_t, reg_th, nop); // PCL <- PCH; PCH <- temp_H (decremented depending on last SUB_0)

	// for interrupt, PC is now decremented by 2 to point to ED B0 again

	ins6(interrupt_m, nop, nop, nop, nop, nop);	// go to interrupt
	ins6(irq_to_f, to_a, ld, acc_a, reg_v, nop); // restore A 

	no_print_cycles_upd_f_error = 1;
	
	print_cycles();  // 25 cycles
}


// The LDDR is not as sophisticated as the LDIR. LDDR is just a simple loop. ACC is untouched.


function z80_lddr(page, opc, name)     //  LDDR   ED B8
{
	z80_opcode(page, opc, name, nop, nop);
    // check if BC=0. Also check interrupt.

	// jp to loop
	ins6(nop, to_t, ld_ir, acc_t, lit16, page_z80_ed)
	ins6(irq_to_f, to_t, ld, acc_t, reg_b, nop)  // delay, get b register

	//no_f_is_irq_error = 1;
	print_cycles();  // 25 cycles
}

// 23-4-2025  new LDIR chooses between classic and prepare

function z80_ldir(page, opc, name)	//   LDIR ED B0
{	z80_opcode(page, opc, name, nop, nop);
 /*
  T <- dec(lit8)  // 7
  T <- and(reg_i)  // get lowest 3 bits of i 
  T <- dec_acc(T)  // 00 now represents C1 mode
  T <- sub (T,1)  // always gives tc=1 except for T==0

  F <- tc, T <- lit16
  dpl <- T + lit32 // address 30

  //  F=0 classic            F=1 fast
  IR <- dpl, page_ed       IR <- lit32, page_ed
  delay.
 */
	ins6(nop,to_t,dec,acc_t,lit8,nop);  // T <- 8
	ins6(nop,to_t,and,acc_t,reg_i,nop); // AND with current bankswitch configuration (get lowest 3 bits)
	ins6(nop,to_t,dec_acc,acc_t,lit0,nop); // dec T
	ins6(nop,to_t,sub,acc_t,lit1,nop);     // sub 1. gives tc=1 except for C1 mode 
	ins6(tc_to_f,to_t,ld,acc_t,lit16,nop); //  T <- 0x10, F <- tc

	if_f_t(in_f(nop, to_t, add, acc_t, lit32, nop), in_t(nop, to_t, inc, acc_t, lit4, nop)); // F0: T <- 0x10 + 0x20  F1: T <- 5	
	// 2-12-2025 change reg_vga_acc to reg_v  (reg_vga_acc may be used in interrupt)
	ins6(nop,to_mem,ld,acc_t,reg_vga_acc,nop); // put 0x30 in reg_vga_acc
	//  F=0  classic  (for C1 mode)                                     F=1  fast (prepare) for non-C1 mode
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, reg_vga_acc, page_z80_ed), in_t(nop, to_dpl, inc_acc, acc_t, lit0, nop)); //   fast: set dpl to 0x06
	if_f_t(in_f(irq_to_f, to_t, ld, acc_t, reg_b, nop),             in_t(nop, to_t, ld_ir, acc_t, dpl, page_z80_ed)); //   fast: jp 0x06 (prepare)
	//
	/* 2-12-2025
	ins6(nop,to_mem,ld,acc_t,reg_v,nop); // put 0x30 in reg_vga_acc (now reg_v)
	//  F=0  classic  (for C1 mode)                                     F=1  fast (prepare) for non-C1 mode
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, reg_v, page_z80_ed), in_t(nop, to_dpl, inc_acc, acc_t, lit0, nop)); //   fast: set dpl to 0x06
	if_f_t(in_f(irq_to_f, to_t, ld, acc_t, reg_b, nop),             in_t(nop, to_t, ld_ir, acc_t, dpl, page_z80_ed)); //   fast: jp 0x06 (prepare)
	*/
	ins6(irq_to_f, to_t, xor, acc_t, lit0, nop)  // delay

	//no_f_is_irq_error = 1;
	print_cycles();  // 25 cycles
}


function z80_ldir_classic(page, opc, name)	//   LDIR Classic ED B4  new 2-12-2025
{	z80_opcode(page, opc, name, nop, nop);

	ins6(nop,to_t,ld,acc_t,lit16,nop); //  T <- 0x10
	ins6(nop, to_t, add, acc_t, lit32, nop); // T <- T + 0x20 result 0x30 in T

	ins6(nop,to_mem,ld,acc_t,reg_vga_acc,nop); // reg_vga_acc <- T
	//ins6(nop,to_mem,ld,acc_t,reg_v,nop); // reg_v <- T

	// jp to loop
	ins6(nop, to_t, ld_ir, acc_t, reg_v, page_z80_ed)
	ins6(irq_to_f, to_t, ld, acc_t, reg_b, nop)  // delay, get b register



	print_cycles();  // 25 cycles
}



//function z80_ldir_loop(page, opc, name)     //  LDIR-LOOP   ED 20   at lit32 (0x20)   5-3-2025 new.
function z80_ldir_loop_cl(page, opc, name)     //  LDIR-CLASSIC   ED 30   at lit32 (0x20)   23-4-2025

			// must have 0x30 in reg_vga_acc. Therefore, it can not be used stand-alone.
{
	z80_opcode(page, opc, name, nop, nop);
    // check if BC=0. Also check interrupt.
	// B register is already in T. 

	ins6_chi(nop, to_dpl, or, acc_t, reg_c, nop); // or with c, check for zero count	

	ins6_pcmin2(nop, to_dpl, dec, acc_t, dpl, nop); // add FF to check for zero, TC=0 if zero

	ins6(tc_to_f, to_dpl, ld, acc_a, reg_l, nop);  // get zero condition in F, and DPL <- reg_l
	//   F=0: BC=0,  stop copying		F=1: nonzero

	// F=0  fetch next instruction
	if_f_t(in_f(next_m, nop, nop, nop, nop, nop), in_t(nop, to_dph, ld, acc_t, reg_h, nop)); //  F=1   DPH <- reg_h // 29-10-2024 change acc_a to acc_t
	ins6(irq_to_f,to_t,ld, acc_t,ext,nop);  //delay; T <- (dph/dpl)  ; get

	ins6(nop,to_dpl,ld, acc_t,reg_e,nop); // DPL <- reg_e
	ins6(nop,to_dph,ld, acc_t,reg_d,nop); // DPH <- reg_d

	ins6(nop, to_mem, ld, acc_t, ext, nop); //   (dph/dpl) <- T ; store

    // now inc HL
	ins6(nop, to_t, inc, acc_t, reg_l, nop);		   // T <- reg_l +1
	ins6(nop, to_mem, ld, acc_t, reg_l, nop);          // reg_l <- T
	ins6(nop, to_t, inc_dtc, acc_t, reg_h, nop);       // T reg_h + 1 (if there was a cy)
	ins6(irq_to_f, to_mem, ld, acc_t, reg_h, nop);     // reg_h <- T
    // now inc DE
	ins6(nop, to_t, inc, acc_t, reg_e, nop);		   // T <- reg_e +1
	ins6(nop, to_mem, ld, acc_t, reg_e, nop);          // reg_e <- T
	ins6(nop, to_t, inc_dtc, acc_t, reg_d, nop);       // T reg_d + 1 (if there was a cy)
	ins6(irq_to_f, to_mem, ld, acc_t, reg_d, nop);     // reg_d <- T
	// now dec BC
	ins6(nop, to_t, dec, acc_t, reg_c, nop);		   // T <- reg_c -1
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);          // reg_c <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_b, nop);       // T reg_b - 1 (if there was a cy)
	
    // jp back to loop	
	ins6(nop, to_t, ld_ir, acc_t, reg_vga_acc, page_z80_ed)	 // 23-4-2025
	//ins6(nop, to_t, ld_ir, acc_t, reg_v, page_z80_ed)	 // 2-12-2025 use reg_v
	ins6(irq_to_f, to_mem, ld, acc_t, reg_b, nop);     // delay, reg_b <- T

	//no_f_is_irq_error = 1;
	print_cycles();  // 21 cycles
}



function z80_lddr_loop(page, opc, name)     //  LDDR-LOOP   ED 10
{
	z80_opcode(page, opc, name, nop, nop);
    // check if BC=0. Also check interrupt.
	// B register is already in T.

	ins6_chi(nop, to_dpl, or, acc_t, reg_c, nop); // or with c, check for zero count	

	ins6_pcmin2(nop, to_dpl, dec, acc_t, dpl, nop); // add FF to check for zero, TC=0 if zero

	ins6(tc_to_f, to_dpl, ld, acc_a, reg_l, nop);  // get zero condition in F, and DPL <- reg_l
	//   F=0: BC=0,  stop copying		F=1: nonzero

	// F=0  fetch next instruction
	if_f_t(in_f(next_m, nop, nop, nop, nop, nop), in_t(nop, to_dph, ld, acc_t, reg_h, nop)); //  F=1   DPH <- reg_h // 29-10-2024 change acc_a to acc_t
	ins6(irq_to_f,to_t,ld, acc_t,ext,nop);  //delay; T <- (dph/dpl)  ; get

	ins6(nop,to_dpl,ld, acc_t,reg_e,nop); // DPL <- reg_e
	ins6(nop,to_dph,ld, acc_t,reg_d,nop); // DPH <- reg_d

	ins6(nop, to_mem, ld, acc_t, ext, nop); //   (dph/dpl) <- T ; store

    // now dec HL
	ins6(nop, to_t, dec, acc_t, reg_l, nop);		   // T <- reg_l -1
	ins6(nop, to_mem, ld, acc_t, reg_l, nop);          // reg_l <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_h, nop);       // T reg_h - 1 (if there was a cy)
	ins6(irq_to_f, to_mem, ld, acc_t, reg_h, nop);     // reg_h <- T
    // now dec DE
	ins6(nop, to_t, dec, acc_t, reg_e, nop);		   // T <- reg_e -1
	ins6(nop, to_mem, ld, acc_t, reg_e, nop);          // reg_e <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_d, nop);       // T reg_d - 1 (if there was a cy)
	ins6(irq_to_f, to_mem, ld, acc_t, reg_d, nop);     // reg_d <- T
	// now dec BC
	ins6(nop, to_t, dec, acc_t, reg_c, nop);		   // T <- reg_c -1
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);          // reg_c <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_b, nop);       // T reg_b - 1 (if there was a cy)
	
    // jp back to loop
	ins6(nop, to_t, ld_ir, acc_t, lit16, page_z80_ed)
	ins6(irq_to_f, to_mem, ld, acc_t, reg_b, nop);     // delay, reg_b <- T
	
	print_cycles();  // 21 cycles
}

// XHAL  21-10-2024
// does XOR H, followed by AND L.
// Used in f_find (file search)

function z80_xhal(page, opc, name)			// XHAL   ED 77  21-10-2024
{   z80_opcode(page, opc, name, nop, nop);

	ins6(nop, to_a, xor, acc_a, reg_h, nop);	// xor h register	
	ins6(nop, to_a, and, acc_a, reg_l, nop);	// and l register	
	final(irq_to_f, to_mem, ld, acc_a, reg_z, nop); // store reg_z
 	print_cycles();  // 
}

// DECZ C  22-10-2024
// does dec c, set/clr Z flag, doesnt affect N flag
// Used in dsk_rdblks

function z80_deczc(page, opc, name)			// DECZ C   ED 76  22-10-2024
{   z80_opcode(page, opc, name, nop, nop);

	ins6(nop, to_t, dec, acc_a, reg_c, nop);	// T <- dec (reg_c)
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);	// store back into c	
	final(irq_to_f, to_mem, ld, acc_t, reg_z, nop); // store T also in reg_z
 	print_cycles();  // 
}



// XORZ reg  22-10-2024
// does XOR reg, set/clr Z flag, doesnt affect N flag
// Used in functions that use SPI

function z80_xorz(page, opc, name,src)			// XORZ reg  page_ix  22-10-2024
{   z80_opcode(page, opc, name, src, nop);
	if (src == ind_hl) 	
	   { src = ext; 
	     ins6(irq_to_f, to_dpl, ld, acc_a, reg_l, nop);
	     ins6(nop, to_dph, ld, acc_t, reg_h, nop); // 29-10-2024 change acc_a to acc_t
	   }
	ins6(nop, to_a, xor, acc_a, src, nop);
	final(irq_to_f, to_mem, ld, acc_a, reg_z, nop); 
 	print_cycles();  // 
}



// end Z80 functions

//-----------------------------------------------------

//	SOUND GENERATOR functions

//----------------------------------------------------

// 18-5-2025

// Sound channels
const PSG_CH_1 = lit33;  // 0x21   20-5-2025
//  CH_1 ENV: 0x20 (reserved for SID)
//  CH_1 BUF: 0x22
//  CH_1 POS: 0x24
//  CH_1 NEG: 0x26
const PSG_CH_2 = lit41;
// PSG_CH_2  0x29   28-5-2025
// PSG_CH_3  0x31   28-5-2025
// PSG_CH_4  0x39   28-5-2025 noise channel





    // There are 4 sound buffers, of 1kB each. All in HW bank1.
	// The basic address will start at 1000, counting up until 13FF. Wrap-around by resetting bit2. Other buffers:
	// 0C00      (1000 minus 400)
	// 1000      basic address 1000 
	// 1400      (1000 plus 400)
	// 1800-1BFF (1000 plus 800)
	// 1C00-1C20 buffer overflow area


function out_psg_regsel(opc,name)   // 0x40  OUT psg_regsel   17-5-2025  select psg register 0 - 13. If PSG was muted, unmute it.
{	opcode_page(page_out, opc, name, nop, nop);
	
	ins6(nop, to_t, asl, acc_t, reg_snd_pth, nop); // 14-5-2025 get mute flag in tc

	ins6(tc_to_f,to_mem,ld,acc_a,reg_ch_sel,nop); // 28-5-2025 select register

	if_f_t(in_f(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset), in_t(nop, to_t, ld, acc_t, lit0, nop));  // F0: jp reg_isa  F1: nop (unmute)

	// sound reg pointer MSB start at 1400. 
	ins6(nop, to_t, ld, acc_t, lit16, nop); // T <- 0x10	
	
	ins6(nop, to_mem, ld, acc_t, reg_snd_pth, nop); //  init pch (unmute)
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); 	

	print_cycles();
}	


function out_psg_data(opc,name)   // 0x41  OUT psg_data   17-5-2025  write data register
{	opcode_page(page_out, opc, name, nop, nop);
	// 28-5-2025
	
	make_literal(to_t,0x37)	;// address of the enable  instruction
	ins6(nop, to_mem, ld, acc_t, reg_kb_tmp, bank1); // save the address, for enable instruction-jump-back
	
	ins6(nop,to_t,ld,acc_t,reg_ch_sel,nop);	// get selection
	ins6(nop,to_t,and,acc_t,reg_0F,nop); // use only bit0-3	
	ins6(nop,to_t,or,acc_t,lit32,nop); // or #20
	ins6(nop,to_dpl,or,acc_t,lit16,nop); // or #10	, result to dpl
	
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_sound); // jp to psg sound register 0 -15
	
	ins6(nop,to_dpl,inc,acc_t,PSG_CH_1,nop); // 1-6-2025  for the ENABLE command, first channel in dpl, #22
	print_cycles();
}	

function out_sound_mode(opc,name)   // 0x43  OUT sound mode   1-9-2025  select ZX-Spectrum sound mode
{	opcode_page(page_out, opc, name, nop, nop);
	// A = 0  select PSG (not implemented here because it is the default at reset)
	// A = 1  ZX-Spectrum mode

	make_literal(to_t,SOUND_STATE_ZX);

	ins6(nop,to_mem,ld,acc_t,reg_sound_state,nop); // to register, that is used to select the device driver

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); 	

	print_cycles();
}


// PSG  AY-3-8910  CONTROL REGISTERS

// 28-5-2025

// Located at #30 - #3F in the sound page

function out_psg_reg(opc,ch,name)   //
{	opcode_page(page_sound, opc, name, nop, nop);
	if (ch==1) 	ins6(nop,to_t,ld,acc_t,PSG_CH_1,nop);
	if (ch==2) 	ins6(nop,to_t,ld,acc_t,PSG_CH_2,nop);
	if (ch==3) 	make_literal(to_t,0x31);
	if (ch==4)  make_literal(to_t,0x39);		

    if (ch!=0)
	  { 	if (opc < 0x38) ins6(nop,to_t,add,acc_t,lit4,nop);  // T <- T + 4 (for period only)	  		
			ins6(nop,to_mem,ld,acc_t,reg_ch_sel,nop);  // select channel 1  (period #25, volume #21)
	  }

if ((opc == 0x30) || (opc == 0x32) ||(opc == 0x34))  // period lsb
 { // the LSB is processed by output port #47
	make_literal(to_t, 0x47) ;
	ins6(nop,to_dpl,add,acc_t,lit0,nop); // move to dpl
	ins6(l_to_f, to_t, ld_ir, acc_t, dpl, page_out); // jp to output port #47
	ins6(nop, to_t, ld, acc_t, lit0, nop); 
 }

if ((opc == 0x31) || (opc == 0x33) ||(opc == 0x35))  // period msb
 { 	// The input, in ACC, is the MSB of periodtime of the PSG. Only bit0-bit3 are used.
	ins6(nop,to_a,and,acc_a,reg_0F,nop); // A <- A and 0F 
	ins6(nop,to_mem,ld,acc_a,reg_vga_acc,nop);  // reg_vga_acc <- A 

	// select CH_POS, control block of positive wave of this channel
	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5
	ins6(nop,to_dpl,dec,acc_t,reg_ch_sel,nop); // channel_positive #24

	// ch_period_msb (bit4-bit1) <-- ACC (bit3-bit0)  // bit0 of ch_period_msb stays the same.
	ins6(nop,to_t,ld,acc_t,ext_msb,bank0); // period msb
	ins6(nop,to_t,and_tst,acc_t,lit1,nop);  // T <- T and_tst 1 (test bit0)
	ins6(nop,to_t,rol_tc,acc_t,reg_vga_acc,nop); // left shift input nibble, append the bit0

	ins6(nop,to_mem,ld,acc_t,ext_msb,bank0)	; // store in positive wave

	// select CH_NEG, control block of negative wave of this channel
	ins6(nop,to_dpl,inc,acc_t,reg_ch_sel,nop); // channel_negative #26
	
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa		
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank0)	; // store in negative wave	
  }
	if (opc == 0x36) // noise period
  {	// 28-5-2025 some noise periods let the system crash. So, temporary, set it to a fixed value (0F) 
    // 6-6-2025 crash not observed any more, with several period times (using OUT #59)
  	//ins6(nop,to_a,ld,acc_a,reg_0F,nop) // c.o. 0607B
	
	ins6(nop,to_dpl,res2,acc_a,lit33,nop); // dpl <- A res2 0x21  // reset bit 0 and bit 5
	ins6(nop,to_t,asl,acc_t,dpl,nop);  // T <- asl (dpl) // now have 00xx xx00
	ins6(nop,to_a,or,acc_t,reg_128,nop); // set bit 7, result in A

	ins6(nop,to_t,ld,acc_t,lit0,nop);	 // T <- 0

	// select CH_POS, control block of positive wave of this channel
	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5
	ins6(nop,to_dpl,dec,acc_t,reg_ch_sel,nop); // channel_positive #24	

	ins6(nop,to_mem,ld,acc_a,ext,bank0)	; // store ACC in period_lsb, positive wave
	// The initializer should set the period_msb and count_hi values to zero.

	// select CH_NEG, control block of negative wave of this channel
	ins6(nop,to_dpl,inc,acc_t,reg_ch_sel,nop); // channel_negative #26

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa 		
	ins6(nop,to_mem,ld,acc_a,ext,bank0)	; // store ACC in period_lsb, negative wave		
  }
 	if (opc == 0x37) // enable bits, 00NNNTTT  active-low enables for tone and noise per channel (channel CBA)	
  { // 1-6-2025
    ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5  
	// the 6 enable bits must be distributed over the channel control areas.
	// This loops 3 times, will have bad IRQ response  9 + 48 = 57 cycles
	// the first channel is in dpl, #22

	// handle TONE bit
	ins6(nop, to_t, and_tst, acc_a, lit1, nop); // test bit0 in A (active low)
	ins6(tc_to_f, to_t, ld, acc_t, lit32, nop); // tc->F, T <- bit5  destination bit	
  	if_f_t(in_f(nop,to_t,or,acc_t,ext_msb,bank1),  //  F: set destination bit (active high)
	       in_t(nop,to_t,res,acc_t,ext_msb,bank1)  );            //  T: clr destination bit
	ins6(nop, to_mem, ld, acc_t, ext_msb, bank1);  // store the byte with the modified bit

	// handle NOISE bit	
	ins6(nop, to_t, and_tst, acc_a, lit8, nop); // test bit3 in A (active low)
	ins6(tc_to_f, to_t, ld, acc_t, reg_128, nop); // tc->F, T <- bit7  destination bit	
  	if_f_t(in_f(nop,to_t,or,acc_t,ext_msb,bank1),  //  F: set destination bit (active high)
	       in_t(nop,to_t,res,acc_t,ext_msb,bank1)  );            //  T: clr destination bit
	ins6(nop, to_mem, ld, acc_t, ext_msb, bank1);  // store the byte with the modified bit
	
	// prepare for next channel

	ins6(nop, to_t, ld, acc_t, dpl, nop); 	//  T <- dpl
	ins6(nop, to_dpl, add, acc_a, lit0, nop); 	// dpl <- A  (A must be shifted right)
	ins6(nop, to_a, and_tst, acc_t, lit16, nop); // test bit4 in record address. If 1, this was ch 3.

	ins6(tc_to_f, to_dph, ld, acc_t, lit1, nop); // dph <- 1, tc_to_f	24-6-2025 new shr

	ins6(nop, to_a, shrnew, acc_a, ext, nop);	// get shifted value from table, into A. tc -> F.	24-6-2025 new shr

  	if_f_t(in_f(nop, to_t, ld_ir, acc_t, reg_kb_tmp, page_sound),  //  F: jp to 'psg_reg_enable'
	       in_t(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset)  );   //  T: this was ch3, stop, jp to ISA

	ins6(nop,to_dpl,add,acc_t,lit8,nop); // dpl <- T + 8  select nxt channel (delay)

  }
 	if ((opc == 0x38) || (opc == 0x39) ||(opc == 0x3A))  // set amplitude for each channel // bit0-3 amplitude, bit4: use-envelope
  { 
	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5 
	ins6(nop,to_dpl,inc,acc_t,reg_ch_sel,nop); // channel_buf #22

	ins6(nop,to_a,res2,acc_a,reg_128,nop); // reset bit7 of A (Noise bit)
	ins6(nop,to_a,res2,acc_a,lit32,nop); // reset bit5 of A (Tone bit)
	
	ins6(nop,to_t,ld,acc_t,ext_msb,bank1); // T <- channel(amplitude)
	ins6(nop,to_t,res2,acc_t,reg_0F,nop);  // clear bit 0-3 in T
	ins6(nop,to_t,res2,acc_t,lit16,nop);  // clear bit 4 in T
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank1); // channel(amplitude) <- T	
	ins6(nop,to_t,or,acc_a,ext_msb,bank1); // T <- A or channel(amplitude) // combine old and new value
		
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
		
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank1); // channel(amplitude) <- T		
  }  
	if (opc == 0x3B) // envelope period lsb (8 bit)
  { // 10-6-2025  lsb is in bank0. Only upper 4 bits are LSB
  	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5
	ins6(nop,to_dpl,dec,acc_t,reg_ch_sel,nop); // channel_buf #20
	ins6(nop,to_mem,ld,acc_a,ext,bank0); // put A in lsb env period time

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); 	
  }  
	if (opc == 0x3C) // envelope period msb (8 bit)
  { // 10-6-2025
  	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5
	ins6(nop,to_dpl,dec,acc_t,reg_ch_sel,nop); // channel_buf #20
	ins6(nop,to_mem,ld,acc_a,ext_msb,bank0); // put A in msb env period time	

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); 	
  }  
	if (opc == 0x3D) // envelope cycle
  { // 10-6-2025
  	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5
	ins6(nop,to_dpl,dec,acc_t,reg_ch_sel,nop); // channel_buf #20
	ins6(nop,to_a,and,acc_a,reg_0F,nop); // reset upper 4 bits in A
	ins6(nop,to_t,and_tst,acc_a,lit4,nop); // test bit2 (attack). If 1, counting goes upwards

	ins6(tc_to_f,to_mem,ld,acc_a,ext_msb,bank2); // write ACC to env cycle (shape), tc_to_f

	// set first volume level to 0 (upwards) or 0F (downwards)

  	if_f_t(in_f(nop,to_t,ld,acc_t,reg_0F,nop),  // F: downwards count, volume start at 0F  13-6-2025
	       in_t(nop,to_t,ld,acc_t,lit0,nop)  ); // T: upwards count, volume start at 0

	ins6(nop,to_mem,ld,acc_t,ext,bank2); // write volume	   

	// now reset the cycle.
	ins6(nop,to_t,ld,acc_t,ext,bank0); // get lsb env period time
	ins6(nop,to_mem,ld,acc_t,ext,bank1); // set lsb counter to period time

	ins6(nop,to_t,ld,acc_t,ext_msb,bank0); // get msb env period time		
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank1); // set msb counter to period time

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); 	
  }      
	if ((opc == 0x3E) || (opc == 0x3F))  // unused
  {
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); 	
  }        

	print_cycles();
}	


/* registers are as follows:
	out_psg_reg(0x30,1,"PSG ch1 period lsb");
	out_psg_reg(0x31,1,"PSG ch1 period msb"); // bit 0-3 only
	out_psg_reg(0x32,2,"PSG ch2 period lsb");
	out_psg_reg(0x33,2,"PSG ch2 period msb"); // bit 0-3 only
	out_psg_reg(0x34,3,"PSG ch3 period lsb");
	out_psg_reg(0x35,3,"PSG ch3 period msb"); // bit 0-3 only
	out_psg_reg(0x36,4,"PSG noise period");   // bit 0-4 only
	out_psg_reg(0x37,0,"PSG enable/");
	out_psg_reg(0x38,1,"PSG ch1 amplitude"); // bit0-3 amplitude, bit4: use-envelope
	out_psg_reg(0x39,2,"PSG ch2 amplitude"); // bit0-3 amplitude, bit4: use-envelope
	out_psg_reg(0x3A,3,"PSG ch3 amplitude"); // bit0-3 amplitude, bit4: use-envelope
	out_psg_reg(0x3B,1,"PSG envelope period lsb");
	out_psg_reg(0x3C,1,"PSG envelope period msb");
	out_psg_reg(0x3D,1,"PSG envelope cycle");  // bit 0-3 only
	out_psg_reg(0x3E,0,"PSG unused");
	out_psg_reg(0x3F,0,"PSG unused");	
*/

// 25-5-2025  two testfunctions, write LSB and MSB of the period time to PSG channel 1

function out_psg_msb(opc,name)   // 0x57  OUT psg_msb   17-5-2025  write period msb
{	opcode_page(page_out, opc, name, nop, nop);

	// put the channel number is reg_ch_sel
	ins6(nop,to_t,ld,acc_t,PSG_CH_1,nop);
	ins6(nop,to_t,add,acc_t,lit4,nop);  // T <- T + 4
	ins6(nop,to_mem,ld,acc_t,reg_ch_sel,nop);  // select channel 1  (#25)

	// The input, in ACC, is the MSB of periodtime of the PSG. Only bit0-bit3 are used.
	ins6(nop,to_a,and,acc_a,reg_0F,nop); // A <- A and 0F 
	ins6(nop,to_mem,ld,acc_a,reg_vga_acc,nop);  // reg_vga_acc <- A 

	// select CH_POS, control block of positive wave of this channel
	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5
	ins6(nop,to_dpl,dec,acc_t,reg_ch_sel,nop); // channel_positive #24

	// ch_period_msb (bit4-bit1) <-- ACC (bit3-bit0)  // bit0 of ch_period_msb stays the same.
	ins6(nop,to_t,ld,acc_t,ext_msb,bank0); // period msb
	ins6(nop,to_t,and_tst,acc_t,lit1,nop);  // T <- T and_tst 1 (test bit0)
	ins6(nop,to_t,rol_tc,acc_t,reg_vga_acc,nop); // left shift input nibble, append the bit0

	ins6(nop,to_mem,ld,acc_t,ext_msb,bank0)	; // store in positive wave

	// select CH_NEG, control block of negative wave of this channel
	ins6(nop,to_dpl,inc,acc_t,reg_ch_sel,nop); // channel_negative #26
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank0)	; // store in negative wave	

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); 
	print_cycles();
}	


function out_psg_lsb(opc,name)   // 0x47  OUT psg_lsb   17-5-2025  write period lsb
{	opcode_page(page_out, opc, name, nop, nop);

	ins6(nop,to_mem,ld,acc_a,reg_vga_acc,nop);  // reg_vga_acc <- A 

	// select CH_POS, control block of positive wave of this channel
	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5
	ins6(nop,to_dpl,dec,acc_t,reg_ch_sel,nop); // channel_positive #24

	ins6(nop,to_t,ld,acc_t,ext_msb,bank0); // period msb
	ins6(nop,to_t,res2,acc_t,lit1,nop);  // reset bit0

	// get ACC, shift it one position to the left
	ins6(nop,to_a,asl,acc_t,reg_vga_acc,nop); 
	ins6(nop,to_t,add_tc,acc_t,lit0,nop);  // the bit, that shifted out ACC, is added to the period_msb

	ins6(nop,to_mem,ld,acc_t,ext_msb,bank0)	; // store to period_msb in positive wave
	
	// select CH_NEG, control block of negative wave of this channel
	ins6(nop,to_dpl,inc,acc_t,reg_ch_sel,nop); // channel_negative #26
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank0)	; // store in negative wave		

	// period_msb is handled, Now do the rest of the ACC contents

	ins6(nop,to_dpl,add,acc_a,lit0,nop); // dpl <- A
	ins6(nop,to_dph,inc,acc_t,lit1,nop); // dph <- 2  select swap table in bank2, 0200-02FF

	ins6(nop,to_t,ld,acc_t,ext,bank2); // get A, nibbles swapped
	ins6(nop,to_dpl,and,acc_t,reg_0F,nop);  // dpl <- T and 0F // select period
	ins6(nop,to_a,asl,acc_t,dpl,nop);  // shift left, now 000pppp0 period time
	ins6(nop,to_a,add,acc_a,lit32,nop);
	ins6(nop,to_a,add,acc_a,lit32,nop); // added #40 to get instruction address for this period time, #40 - #5E

	// select CH_POS, control block of positive wave of this channel
	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5
	ins6(nop,to_dpl,dec,acc_t,reg_ch_sel,nop); // channel_positive #24	

	ins6(nop,to_mem,ld,acc_a,ext,bank0)	; // store ACC in period_lsb, positive wave

	ins6(nop,to_t,res2,acc_t,reg_0F,nop); // fraction in bit4-7
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank1)	; // store T in fraction, positive wave	

	// select CH_NEG, control block of negative wave of this channel
	ins6(nop,to_dpl,inc,acc_t,reg_ch_sel,nop); // channel_negative #26
	ins6(nop,to_mem,ld,acc_a,ext,bank0)	; // store ACC in period_lsb, negative wave	
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank1)	; // store T in fraction, negative wave	

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); 
	print_cycles();
}	

function out_psg_noisefreq(opc,name)   // 0x59  OUT psg_msb   26-5-2025  write noise period 0 - 31
{	opcode_page(page_out, opc, name, nop, nop);
	// TODO  clear the unused bits in A

	// put the channel number in reg_ch_sel
	ins6(nop,to_t,ld,acc_t,PSG_CH_1,nop);
	ins6(nop,to_t,add,acc_t,lit4,nop);  // T <- T + 4
	
	ins6(nop,to_mem,ld,acc_t,reg_ch_sel,nop);  // select channel 1  (#25)

	ins6(nop,to_dpl,res2,acc_a,lit33,nop); // dpl <- A res2 0x21  // reset bit 0 and bit 5
	ins6(nop,to_t,asl,acc_t,dpl,nop);  // T <- asl (dpl) // now have 00xx xx00
	ins6(nop,to_a,or,acc_t,reg_128,nop); // set bit 7, result in A

	ins6(nop,to_t,ld,acc_t,lit0,nop);	 // T <- 0

	// select CH_POS, control block of positive wave of this channel
	ins6(nop,to_dph,inc,acc_t,lit4,nop); // dph <- 5
	ins6(nop,to_dpl,dec,acc_t,reg_ch_sel,nop); // channel_positive #24	

	ins6(nop,to_mem,ld,acc_a,ext,bank0)	; // store ACC in period_lsb, positive wave
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank0)	; // store 0 in period_msb, positive wave
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank2)	; // set count_hi to 0		

	// select CH_NEG, control block of negative wave of this channel
	ins6(nop,to_dpl,inc,acc_t,reg_ch_sel,nop); // channel_negative #26
	ins6(nop,to_mem,ld,acc_a,ext,bank0)	; // store ACC in period_lsb, negative wave	
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank0)	; // store 0 in period_msb, negative wave	
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank2)	; // set count_hi to 0			

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); 

	print_cycles();
}

const bank_sound = bank1;  // should be bank1. Can set it to bank3 temporary for checking the effect for writing ?

// sound channels. Must be odd values, with distance 8.




//opcodes in sound page, for PSG: 

const PSG_NXT128 = lit40;  // 0601F
const opc_psg_nxt128 = 40;

const PSG_SQ_LOOP = lit20;  // 20-5-2025
const opc_psg_sq_loop = 0x14;

const PSG_CH_START = lit1;  // 12-6-2025
const opc_psg_ch_start = 1;

const PSG_CH_VOLUME = lit33;  // 12-6-2025
const opc_psg_ch_volume = 33;

const PSG_ENVELOPE = lit8;  // 12-6-2025
const opc_psg_envelope = 8;

const PSG_CH_END = lit4;  // 20-5-2025
const opc_psg_ch_end = 4;

const PSG_INT = reg_0F;  // 25-5-2025 interrupt
const opc_psg_int = 15;

// sound channel structure

// CH_NEG:  (dpl can be different for both half-periods)
//   bank0: ch_period_lsb  +1: ch_period_msb
//   bank1: ch_volume      +1: ch_fraction
//   bank2: ch_nxtdpl      +1: ch_count_hi  // nxtdpl has the other polarity, CH_POS
//
// CH_POS:  (dpl can be different for both half-periods, that is CH_NEG)
//   bank0: ch_period_lsb  +1: ch_period_msb
//   bank1: ch_volume      +1: ch_fraction
//   bank2: ch_nxtdpl      +1: ch_count_hi  // nxtdpl has the other polarity, CH_NEG
//
// CH_BUF:  (buffer functions)
//   bank0: ch_buf_msb  +1: ch_buf_frac_save     // ch_buf_msb is the MSB of the start  of the 1kB buffer for this ch.
//   bank1: ch_buf_pol  +1: amplitude N.TMVVVV   // ch_buf_pol has either CH_POS or CH_NEG
//   bank2: ch_buf_pcl  +1: ch_buf_pch
//
// CH_ENV:  (envelope functions)  CH-1 is used to store envelope parameters (also for the other channels)
//   bank0: env_period_lsb  +1: env_period_msb    // as programmed in psg register 11 and 12
//   bank1: env_counter_lsb +1: env_counter_msb   // 
//   bank2: env_volume      +1: env_cycle         // cycle as programmed in psg register 13. Volume as calculated according to this envelope.
//   tbd
//
// Example, for CH-1 (defined as 0x21), the sections are:
//   ch_env  0x20
//   ch_buf  0x22
//   ch_pos  0x24
//   ch_neg  0x26
// In each of these four sections, the six bytes are directly accessible, with a combination of:
//   ext (0x20) or ext_msb (0x21)
//   bank0, bank1 or bank2
// So for each channel, there are 24 bytes available.
//
// There are four sound channels, here are the LSB addresses (MSB is 5):
// PSG_CH_1  0x21              channel 1 (has envelope data in CH_ENV)
// PSG_CH_2  0x29   28-5-2025  channel 2
// PSG_CH_3  0x31   28-5-2025  channel 3
// PSG_CH_4  0x39   28-5-2025  (noise channel)
//
// Note that each channel has space to define its own envelope, but the AY-3-8910 uses just a single, common envelope.
//

 

//  S Q U A R E   W A V E   S A M P L E S 

// generate a half-period of square wave. nr = 0-15 cycles per half-period

function psg_square_sample(nr)
{   opc = 0x40 + 2* nr; // opcodes #40 - #5E (even only)
	opcode_page(page_sound, opc, "PSG_SQ "+nr, nop, nop);

	// irq must be in F
	// DPL must point to CH_POS or CH_NEG
	// T must be PCL or compl(PCL)
  
  	if_f_t(in_f(nop,to_t,ld_ir,acc_t,PSG_INT,page_sound),  // F: JUMP interrupt,
	       in_t(nop,to_t,add,acc_t,reg_128,nop)  );       //  T: T <- T + 128, update tc		   

	ins6(tc_to_f,to_t,ld,acc_t,ext,bank1);  // T <- sample, F <- tc	   

  	if_f_t(in_f(c_to_f,to_t,ld_ir,acc_t,PSG_NXT128,page_sound),  //  F: JUMP psg_nxt128, f <- c
	       in_t(nop,to_a,add,acc_a,ext_msb,bank1)  );            //  T:   A += fraction, upd tc
		   
    // something must be here... as delay for JUMP		
	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop) ; // for the moment, place a NOP here. But set F=1 if extra fraction sample must be placed  

	i = nr;
	while (i > 0)  // place the requested amount of samples.
	 { ins6(nop,to_mem,ld,acc_t,pc_pp,bank_sound);  // place sample from T to (pc++) in sound buffer bank
		i = i -1;	
	 }

	// now, if the fraction produced a carry, place extra sample
 	if_f_t(in_f(nop,to_t,xor,acc_t,lit0,nop),
	       in_t(nop,to_mem,ld,acc_t,pc_pp,bank_sound)  ); // F: nop  T: place sample

	ins6(nop,to_t,dec,acc_t,ext_msb,bank0); // test the period_MSB, update tc

	// possible problem: DPL is changed after the period_msb was read...  problem for non-50/50 duty cycle ?
	ins6(tc_to_f,to_dpl,ld,acc_t,ext,bank2);  // get nxtdpl (points to second half of the wave), f <- tc

	// if F=0, the period_msb was zero, and we can directly jump to placing 0-15 samples
	// at the same time put cy in F
 	if_f_t(in_f(c_to_f,to_t,ld_ir,page_sound,ext,bank0),    // F0: jump to period_lsb (in ext,bank0), F <- CY
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  ); // F1: nop

	// in the delay, fill T with pcl or compl(pcl) (choosen by CY that is in F), and F <- irq
 	if_f_t(in_f(irq_to_f,to_t,ld,acc_t,pcl,nop),    // F0: 
	       in_t(irq_to_f,to_t,compl,acc_t,pcl,nop)  );

	// next part is for low frequencies where period_msb is not zero.  20-5-2025

	ins6(nop,to_t,ld,acc_t,ext_msb,bank0);  // T <- period_msb
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank2)   //  count_hi <- T

 	ins6(c_to_f,to_t,ld_ir,acc_t,PSG_SQ_LOOP,page_sound);   // jump to PSG_SQ_LOOP, F <- CY
	     
	// in the delay, fill T with pcl or compl(pcl) (choosen by CY that is in F), and F <- irq
 	if_f_t(in_f(irq_to_f,to_t,ld,acc_t,pcl,nop),    
	       in_t(irq_to_f,to_t,compl,acc_t,pcl,nop)  );	

	print_cycles();

}

//  N O I S E   S A M P L E S 


function psg_noise_sub(samples,frac)
 {	// here, to generate a new random bit
	// Galois type, from https://en.wikipedia.org/wiki/Linear-feedback_shift_register 
	ins6(nop,to_a,asl,acc_t,reg_noise_lsb,nop);  // A <- asl(noise_lsb)
	ins6(nop,to_t,rol_tc,acc_t,reg_noise_msb,nop);  // T <- rol_tc(noise_msb) 
	ins6(tc_to_f,to_mem,ld,acc_t,reg_noise_msb,nop); // noise_msb <- T, f <- tc

  	if_f_t(in_f(nop,to_dpl,ld,acc_t,ext,bank2),     // F: dpl <- nextdpl  // toggle output bit
	       in_t(nop,to_a,xor,acc_a,reg_psg_tmp,nop)  ); //  T: A <- A xor 0x2D (the constant is in reg_psg_tmp)

	ins6(nop,to_mem,ld,acc_a,reg_noise_lsb,nop);  // noise_lsb <- A

	ins6(nop,to_t,ld,acc_t,ext,bank1); // get the sample in T

	// now place the amount of samples 1 - 4
	i = samples;
	while (i > 0)  // place the requested amount of samples.
	 { ins6(nop,to_mem,ld,acc_t,pc_pp,bank_sound); i--; } // place sample from T to (pc++) in sound buffer bank
	// might also place a fractional sample:
    if (frac ==1) ins6(nop,to_mem,ld,acc_t,pc_pp,bank_sound);
 }



function psg_noise_samples(nr)
{   opc = 0x80 + 4 * nr; // opcodes #80 - #8C (can take up to 50 cycles each)
	
	opcode_page(page_sound, opc, "PSG_NOISE "+nr, nop, nop);

	// irq must be in F, T must be PCL or compl(PCL),  DPL must point to CH_POS or CH_NEG 
  
  	if_f_t(in_f(nop,to_t,ld_ir,acc_t,PSG_INT,page_sound),  // F: JUMP interrupt,
	       in_t(nop,to_t,add,acc_t,reg_128,nop)  );       //  T: T <- T + 128, update tc		   

	ins6(tc_to_f,to_t,ld,acc_t,ext,bank1);  // T <- sample, F <- tc	   (sample unused ?)

  	if_f_t(in_f(c_to_f,to_t,ld_ir,acc_t,PSG_NXT128,page_sound),  //  F: JUMP psg_nxt128, f <- c
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  );            //  T:  nop

    // something must be here... as delay for JUMP		
	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop) ; // for the moment, place a NOP here. But set F=1 if extra fraction sample must be placed  

	var s = (nr>>2) +1;    // s = 1 - 4
	var frac = nr & 0x03 ; // values 0 - 3	
	if (frac==0)
	   { psg_noise_sub(s,0); psg_noise_sub(s,0); psg_noise_sub(s,0); psg_noise_sub(s,0); } 
	else if (frac==1)
	   { psg_noise_sub(s,1); psg_noise_sub(s,0); psg_noise_sub(s,0); psg_noise_sub(s,0); }   
	else if (frac==2)
	   { psg_noise_sub(s,1); psg_noise_sub(s,0); psg_noise_sub(s,1); psg_noise_sub(s,0); } 
	else if (frac==3)
	   { psg_noise_sub(s,1); psg_noise_sub(s,0); psg_noise_sub(s,1); psg_noise_sub(s,1); } 	    	   

	// Jump back to beginning. at the same time put cy in F
 	ins6(c_to_f,to_t,ld_ir,page_sound,ext,bank0);    // jump to period_lsb (in ext,bank0), F <- CY

	// in the delay, fill T with pcl or compl(pcl) (choosen by CY that is in F), and F <- irq
 	if_f_t(in_f(irq_to_f,to_t,ld,acc_t,pcl,nop),    // F0: 
	       in_t(irq_to_f,to_t,compl,acc_t,pcl,nop)  );

	print_cycles();

}



function psg_functions()
{
	// ******  V_SOUND. Save application registers PCH/PCL, ACC and some flags, and do sound processing  19-5-2025
	// sound processing can take some time, and it can be interrupted by the video scanline interrupt.
	// The output of the sound samples is not in this section (that is in the scanline interrupt).

	opcode_page(page_reset, 0x64, 'v_sound', nop, nop);  // video_frame command #64 is sound. Must occur 3 times in the frame.

	// This will not interrupt the video output, but it could interrupt the blitter !

	ins6(nop,to_t,asl,acc_t,reg_snd_pth,nop);  // check if PSG is enabled, then tc=0  // actually not needed, if not enabled, v_sound does no occur.

	// first see if there is room in the buffer to place ~256 samples

	ins6(nop,to_dph,inc,acc_t,lit4,nop);  // dph <- 5  // msb of channel buffers

	ins6(dtc_to_f,to_t,ld,acc_t,PSG_CH_1,nop);  // first sound channel, F <- dtc
	//ins6(h_to_f,to_t,ld,acc_t,PSG_CH_1,nop);  // first sound channel, F <- dtc	1-10-2025 test, never enable sound (TEST only)
	
	ins6(nop, to_mem, ld, acc_t, reg_snd_ch, nop);	// select first sound channel	
	// have to fill dpl here with ch that has buffer #1400, must be first sound channel (changed to #1000 24-5-2025)

 	// 8-6-2025 C:
 	if_f_t(in_f(nop, to_dpl, inc, acc_t, PSG_CH_2, nop),    // F0: reg_sound_ch + 1 --> is CH_BUF of ch 2 (buf at #1000)
	       in_t(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset)  ); // F1: jump back to user program if PSG not enabled

	ins6(nop,to_t,inc,acc_t,ext_msb,bank2);  // get ch_buf_pch, increment it, move to T. (also delay)

	ins6(nop,to_t,res2,acc_t,lit4,nop);      // reset bit2, to wrap back to beginning	, for #1000 buffer  0524G

	/* replace by two instructions, 0523A
	ins6(nop,to_t,xor_tst,acc_t,reg_snd_pth,nop);	    // compare with the output pointer. tc=0 if equal
	*/
	ins6(nop,to_t,xor,acc_t,reg_snd_pth,nop);	    // compare with the output pointer. tc=0 if equal
	ins6(nop,to_t,sub,acc_t,lit1,nop);		 // tc=0 if equal

	ins6(tc_to_f,to_mem, ld, acc_a, reg_vga_acc, nop);  // save ACC, F <- tc
	//ins6(tc_to_f,to_mem, ld, acc_a, reg_psg_acc, nop);  // 1-10-2025  save ACC, F <- tc  temp test

 	if_f_t(in_f(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset),    // F0: jump back to user program if no space in buffer
	       in_t(nop, to_t, ld, acc_t, pcl, nop)  ); // F1:  get pcl move it to t

	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // store pcl in reg_tl temporary location (in delay)

    ins6(nop, to_pch, ld, acc_t, lit0, nop);   // write to pch to get pch into pcl
	ins6(nop, to_t, ld, acc_t, pcl, nop); // t <- pcl (this is actually pc-msb)
	ins6(nop, to_mem, ld, acc_t, reg_th, nop); // store pcl in reg_th temporary location)		
  
    // save cy flag. Other flags are not used in the sound processor
	ins6(nop, to_t, rol, acc_t, lit0, nop);  // shift left 0000000C  and put cy in bit0  27-5-2025 must be to_t !	
	ins6(nop, to_mem, ld, acc_t, reg_vga_flags, nop); 	  // cy to reg_vga_flags
	
	// registers ACC, PCH/PCL, CY are saved now

	// have to save ISA
	ins6(nop,to_t,ld,acc_t,reg_isa,nop);  // get ISA
	ins6(nop, to_mem, ld, acc_t, reg_vga_lsb, nop); // store ISA lsb of video line address, video will not be used during PSG

	make_literal(to_t, ISA_PSG); // ISA_PSG is #3B
	ins6(nop,to_mem,ld,acc_t,reg_isa,nop);	// set ISA to PSG, for correct return after interrupt

	make_literal(to_t, 0x2D); //  constant for noise generator 
	ins6(nop,to_mem,ld,acc_t,reg_psg_tmp,nop); // save for noise generation

	//  start the first sound channel 

    ins6(nop, to_t, ld_ir, acc_t, PSG_ENVELOPE, page_sound); // jump to psg_ch_envelope  12-6-2025	
	ins6(null_m, nop, nop, nop, nop, nop);	

    print_cycles();

	// ********************************************

	// The CY flag tells if we're in the first or second 128 bytes of a 256 byte section
	// cy is already in F

	opcode_page(page_sound, opc_psg_nxt128, "PSG_NXT128", nop, nop);   //  switch to the next section of 128 samples

	ins6(c_to_f,to_t,xor,acc_t,lit0,nop); // c_to_f here, 1-6-2025

	// previous section did F <- CY
	ins6(nop,to_t,xor,acc_t,lit0,cpl_c) ; // nop, complement cy.

  	if_f_t(in_f(nop, to_t, ld, acc_a, dpl, nop),  // F:  T <- dpl  save CH_POS or CH_NEG
	       in_t(nop,to_t,ld_ir,acc_t,PSG_SQ_LOOP,page_sound)  );       // T: JUMP PSG_SQ_LOOP

	// in the delay, fill T with pcl or compl(pcl) (choosen by CY that is in F), and F <- irq
	// The result here is only used of prev cycle did the jump
	/*  not swapped:
 	if_f_t(in_f(irq_to_f,to_t,ld,acc_t,pcl,nop),    
	       in_t(irq_to_f,to_t,compl,acc_t,pcl,nop)  );
	*/
	// swap the T and F sections, because the F flag is the CY BEFORE it was complemented. ucode0522E
	// note that for F=1, this is a delay instruction for the jmp to psg_sq_loop.
 	if_f_t(in_f(nop, to_dpl, inc, acc_t, reg_snd_ch, nop),  // F0: reg_sound_ch + 1 --> is CH_BUF  
	       in_t(irq_to_f,to_t,ld,acc_t,pcl,nop)  );	

	ins6(nop,to_t,xor,acc_t,lit0,nop);   // nop (delay) // 0530G ten einde raad

	ins6(nop,to_mem,ld,acc_t,ext,bank1); 	  //  ch_buf_pol <- T  save the polarity in the ch_buf_pol

	// save pch/pcl and accumulated fraction in channel buffer
	ins6(nop, to_t, ld, acc_t, pcl, nop); //  get pcl move it to t
	ins6(nop, to_mem, ld, acc_t, ext, bank2); // store pcl in ch_buf_pcl
    ins6(nop, to_pch, ld, acc_t, lit0, nop);   // write to pch to get pch into pcl

	ins6(nop, to_t, ld, acc_t, pcl, nop); // t <- pcl (this is actuall pc-msb)
    ins6(nop, to_pch, add, acc_t, lit0, nop); // pch <- T ; to get "pch|0" in Program counter

	ins6(nop, to_mem, ld, acc_t, ext_msb, bank2); // store pch in ch_buf_pch

	ins6(nop, to_mem, ld, acc_a, ext_msb, bank0); // store accumulated fraction in ch_buf_frac_save

	// check if we're over the end of the 1kB buffer

	ins6(nop,to_t,ld,acc_t,ext,bank0);	 // ch_buf_msb, the start of the 1kB buffer for this ch.
	ins6(nop,to_t,add,acc_t,lit4,nop);   // add 4
	/* replace next line by 2 instr.  0523A
	ins6(nop,to_t,xor_tst,acc_t,ext_msb,bank2);	 // compare with ch_buf_pch. If equal, we are over the buffer end
	*/
	ins6(nop,to_t,xor,acc_t,ext_msb,bank2);	 // compare with ch_buf_pch. If equal, we are over the buffer end
	ins6(nop,to_t,sub,acc_t,lit1,nop);		 // tc=0 if equal

	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop);  // nop, F <- tc
  	if_f_t(in_f(nop,to_t,xor,acc_t,lit0,nop),              // F: nop
	       in_t(nop,to_t,ld_ir,acc_t,PSG_CH_END,page_sound)  ); // T: JUMP psg_ch_end  // not at buffer end, no correction needed

	// correction when the last samples were placed just after the end of the buffer
	// these last samples will be copied to the beginning		   

	ins6(nop,to_t,ld,acc_t,ext,bank0);	     // T <- ch_buf_msb (also delay)
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank2); //  ch_buf_pch <- T  set buffer pointer back to start

	// pch|pcl points to the section just outside the buffer
	ins6(nop,to_dph,ld,acc_t,ext,bank0);	  // dph <- ch_buf_msb
	ins6(nop,to_dpl,ld,acc_t,lit0,nop);		  // dpl <- 0   // dpl now points to the start of the buffer

	// pcode0529D c.o.
	i = 21;  // 27-5-2025 changed from 16 to 21 (Noise needs max. 20)
	while (i >0)  // copy 21 samples that fell outside the buffer to the start of the buffer
	  { ins6(nop,to_t,ld,acc_t,pc_pp,bank_sound);	// load sample, inc pc   // 0607D comm out
		ins6(nop,to_mem,ld,acc_t,ext,bank_sound);   // store sample   
	
		ins6(nop,to_dpl,inc,acc_t,dpl,nop);    // inc dpl
		i--;
	  }
	// done. 

	ins6(nop,to_t,ld_ir,acc_t,PSG_CH_END,page_sound) ;  // jp to psg_ch_end
	ins6(nop,to_t,xor,acc_t,lit0,nop);   // nop (delay)

	print_cycles();	

	// ********************************************

	// psg_sq_loop. Starting point for sound actions. (Squarewave)

	// needs as input:
	// CY flag, F = IRQ, T = pcl or compl(pcl), dpl = ch_pos or ch_neg

	opcode_page(page_sound, opc_psg_sq_loop, "PSG_SQ_LOOP", nop, nop);   //  

	// irq must be in F 
  	if_f_t(in_f(nop,to_t,ld_ir,acc_t,PSG_INT,page_sound),  // F: JUMP interrupt,
	       in_t(nop,to_t,add,acc_t,reg_128,nop)  );       // T: T <- T + 128, (update tc)		   

	ins6(tc_to_f,to_t,ld,acc_t,ext,bank1);  // T <- sample, F <- tc	   

  	if_f_t(in_f(c_to_f,to_t,ld_ir,acc_t,PSG_NXT128,page_sound),   //  F: JUMP psg_nxt128, F <- C
	       in_t(nop,to_t,dec,acc_a,ext_msb,bank2)  ); // 	 T: T <- dec(count_hi), upd tc		   

    // something must be here... as delay for JUMP		
	// prev line c_to_f but here it does tc_to_f...  wrong !
	//ins6(tc_to_f,to_t,xor,acc_t,lit0,nop) ; // for the moment, place a NOP here.   
	// 0524B 
	ins6(nop,to_t,xor,acc_t,lit0,nop) ;     // a real NOP, followed by writing F
	ins6(dtc_to_f,to_t,xor,acc_t,lit0,nop) ; // for the moment, place a NOP here.   	


//  ***** following part must be commented-out for fixed freq test

	// if F=0, the count_hi was zero, and we can directly jump to placing 0-15 samples
	// at the same time put cy in F
 	if_f_t(in_f(c_to_f,to_t,ld_ir,page_sound,ext,bank0),    // F0: jump to period_lsb (in ext,bank0), F <- CY
	       in_t(nop,to_mem,ld,acc_t,ext_msb,bank2)  ); // F1: store the decremented count_hi

	// in the delay, fill T with pcl or compl(pcl) (choosen by CY that is in F), and F <- irq
	// The result here is only used if prev cycle did the jump
 	if_f_t(in_f(irq_to_f,to_t,ld,acc_t,pcl,nop),    // F0: 
	       in_t(irq_to_f,to_t,compl,acc_t,pcl,nop)  );	

	ins6(nop,to_t,ld,acc_t,ext,bank1);  // get the sample (volume)		   

//   ***** the comment-out until here

// ****** for fixed-frequency test, insert following
/*	
	ins6(nop,to_dpl,ld,acc_t,ext,bank2);  // get nxtdpl (points to second half of the wave)

	//ins6(nop,to_t,ld,acc_t,dpl,nop);  // temp: instead of volume, get the channel pos/neg address
	ins6(nop,to_t,ld,acc_t,ext,bank1);  // get the sample (volume)	0524F
*/	
//  ****** end fixed-frequency test

	i = 16;
	while (i > 0)  // place 16 samples.
	 { 
		ins6(nop,to_mem,ld,acc_t,pc_pp,bank_sound);  // place sample from T to (pc++) in sound buffer bank		
		i = i -1;	
	 }
	 
 	ins6(c_to_f,to_t,ld_ir,acc_t,PSG_SQ_LOOP,page_sound);   // jump to PSG_SQ_LOOP, F <- CY
	     
	// in the delay, fill T with pcl or compl(pcl) (choosen by CY that is in F), and F <- irq
 	if_f_t(in_f(irq_to_f,to_t,ld,acc_t,pcl,nop),    
	       in_t(irq_to_f,to_t,compl,acc_t,pcl,nop)  );

	print_cycles();	


	// ********************************************	

	// psg_int.  Interrupt for sound

	opcode_page(page_sound, opc_psg_int, "PSG_INT", nop, nop);   //  

	// save dpl, that indicates POS or NEG
  	ins6(nop, to_t, ld, acc_a, dpl, nop);  //   T <- dpl  save CH_POS or CH_NEG
 	ins6(nop, to_dpl, inc, acc_t, reg_snd_ch, nop);  // reg_sound_ch + 1 --> is CH_BUF  

	ins6(nop,to_mem,ld,acc_t,ext,bank1); 	  //  ch_buf_pol <- T  save the polarity in the ch_buf_pol

	ins6(nop, to_t, ld_ir, acc_t, reg_128, page_z80_ed); // interrupt 
	ins6(nop, to_t, ld, acc_t, lit0, nop);	 // 
	print_cycles();	

	// ********************************************	

	opcode_page(page_reset, ISA_PSG, "GPSG", nop, nop);  // used by return from interrupt, back to PSG
	// The interrupt has preserved ACC, CY and PCH/PCL

	ins6(nop, to_dpl, inc, acc_t, reg_snd_ch, nop);   // reg_sound_ch + 1 --> is CH_BUF	
	ins6(nop,to_dph,inc,acc_t,lit4,nop);  // dph <- 5  msb of channel buffers
	ins6(nop,to_dpl,ld,acc_t,ext,bank1); 	  // dpl <- ch_buf_pol  250522C	

 	ins6(c_to_f,to_t,ld_ir,acc_t,PSG_SQ_LOOP,page_sound);   // jump to PSG_SQ_LOOP, F <- CY
	     
	// in the delay, fill T with pcl or compl(pcl) (choosen by CY that is in F), and F <- irq
 	if_f_t(in_f(irq_to_f,to_t,ld,acc_t,pcl,nop),    
	       in_t(irq_to_f,to_t,compl,acc_t,pcl,nop)  );
	
	print_cycles();		

	// ********************************************

	// 10-6-2025 psg_envelope. Calculate the envelope.
	// then go to PSH_CH_VOLUME to calculate the volume for each channel.

	opcode_page(page_sound, opc_psg_envelope, "PSG_ENVELOPE", nop, nop);   //  

	make_literal(to_t, 0x40); //  value 64
	ins6(nop,to_mem,ld,acc_t,reg_psg_tmp,nop); // save 

	// get the CH_BUF in DPL 
	ins6(nop,to_dpl,dec,acc_t,reg_snd_ch, nop);   // reg_sound_ch - 1 --> is CH_ENV of channel 1
	ins6(nop,to_dph,inc,acc_t,lit4,nop);  // dph <- 5  msb of channel buffers. 

	// decrement the envelope period
	ins6(nop,to_t,ld,acc_t,ext,bank1); // get lsb counter
	ins6(nop,to_t,sub,acc_t,reg_psg_tmp,nop); // subtract 64.
	ins6(nop,to_mem,ld,acc_t,ext,bank1); // store decremented lsb counter

	ins6(nop,to_t,dec_dtc,acc_t,ext_msb,bank1); // get msb counter, decrement depending on carry
	ins6(tc_to_f,to_mem,ld,acc_t,ext_msb,bank1); // store decremented msb counter, F <- tc

	ins6(nop,to_t,ld,acc_t,ext,bank2); // get volume
	ins6(nop,to_mem,ld,acc_t,reg_psg_tmp,nop); // save envelope volume, for volume section to use

	// if the decrement was possible (tc=1), jump to volume section
 	if_f_t(in_f(nop,to_t,xor,acc_t,lit0,nop),     // F0: nop 
	       in_t(nop, to_t, ld_ir, acc_t, PSG_CH_VOLUME, page_sound)  ); //	F1: jp to volume

	// subtract was not possible. Reload the counter.
	ins6(nop,to_t,ld,acc_t,ext,bank0); // get lsb env period time (also delay)
	ins6(nop,to_mem,ld,acc_t,ext,bank1); // set lsb counter to period time

	ins6(nop,to_t,ld,acc_t,ext_msb,bank0); // get msb env period time		
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank1); // set msb counter to period time

	
	// Now increment or decrement the volume, depending on bit 2 (attack) of shape/cycle control
	ins6(nop,to_t,ld,acc_t,lit4,nop); // get bit2 to T
	
	// Now increment or decrement the volume, depending on bit 5 (direction) of shape/cycle control	

	ins6(nop,to_t,and_tst,acc_t,ext_msb,bank2); // test this bit in shape/cycle control	
	ins6(tc_to_f,to_t,ld,acc_t,lit0,nop);  // F=1 if the bit was 1 (count up)

	// increment or decrement volume, result in T
 	if_f_t(in_f(nop,to_t,dec,acc_t,ext,bank2),     // F0: count down
	       in_t(nop, to_t, inc, acc_t, ext,bank2)  ); //	F1: count up

	// find out if the volume went out of range. Dont modify the value in T.
	// If one or more of the upper 4 bits are 1, we're out of range
	ins6(nop,to_a,res2_tst,acc_t,reg_0F,nop); // reset bit 0-3. And test the result. Destroys A register.
	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop); // tc -> F, nop
	// if F=1, out of range.

 	if_f_t(in_f(nop,to_mem,ld,acc_t,reg_psg_tmp,nop),     // F0: save envelope volume, for volume section to use
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  ); //	F1: nop

 	if_f_t(in_f(nop, to_t, ld_ir, acc_t, PSG_CH_VOLUME, page_sound),  // F0: jump to volume
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  ); //	F1: out of range, nop

 	if_f_t(in_f(nop,to_mem,ld,acc_t,ext,bank2),     // F0: in delay, store the new volume T, now we know it is valid.
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  ); //	F1: nop

	// so, the volume can not be further incremented or decremented

	// what to do now ? depends on the ENVELOPE SHAPE/CYCLE CONTROL !  That is in ext_msb,bank2.

	// 13-6-2025
	// First test the Alternate bit (bit 1)	
	ins6(nop,to_t,inc,acc_t,lit1,nop);   // get bit 1 (value 2) in T
	ins6(nop,to_t,and_tst,acc_t,ext_msb,bank2); // test shape/cycle control for bit 1 (alternate)
	ins6(tc_to_f,to_t,ld,acc_t,ext_msb,bank2);  // get shape/cycle control in T, F=1 if the bit was 1
	ins6(nop,to_a,ld,acc_t,ext,bank2);   // get current volume in A

	if_f_t(in_f(nop,to_a,xor,acc_a,lit0,nop),  // F0: not alternate, nop
	       in_t(nop,to_t,xor,acc_t,lit4,nop)  ); //	F1: alternate, toggle direction bit (bit 2)

 	if_f_t(in_f(nop,to_a,xor,acc_a,lit0,nop),  // F0: nop
	       in_t(nop,to_a,xor,acc_a,reg_0F,nop)  ); //	F1: alternate, toggle the volume in A ( 0 -> 15, 15 -> 0)

	ins6(nop,to_mem,ld,acc_t,ext_msb,bank2); // store new state

	// 17-6-2025 test continue-bit
	ins6(nop,to_t,ld,acc_t,ext_msb,bank2);  // get shape/cycle control in T
	ins6(nop,to_t,and_tst,acc_t,lit8,nop); // test bit 3.
	ins6(tc_to_f,to_t,ld,acc_t,lit1,nop); // T <- 1  (HOLD) , tc -> F
	// F=0 not continue   F=1 continue
 	if_f_t(in_f(nop,to_a,ld,acc_a,lit0,nop),    // F0: set volume zero
	       in_t(nop,to_a,xor,acc_a,lit0,nop)  ); // F1: nop

 	if_f_t(in_f(nop,to_mem,ld,acc_t,ext_msb,bank2),    // F0: write 1 to shape/control. Will set direction down, hold=1
	       in_t(nop,to_t,ld,acc_t,ext_msb,bank2)  );   // F1: re-load shape/control
	// 17-6-2025 end

	// Next, test the Hold bit (bit 0). The shape/control is still in T
	ins6(nop,to_t,and_tst,acc_t,lit1,nop); // test bit 0 (hold)
	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop); // nop, tc -> F

 	if_f_t(in_f(nop,to_a,xor,acc_a,reg_0F,nop),           // F0: not HOLD,  toggle the volume in A ( 0 -> 15, 15 -> 0)
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  ); //	F1: HOLD , nop

	ins6(nop,to_mem,ld,acc_a,ext,bank2);   // store A as new volume
	ins6(nop,to_mem,ld,acc_a,reg_psg_tmp,nop); // save envelope volume, for volume section to use	

 	if_f_t(in_f(nop, to_t, ld_ir, acc_t, PSG_CH_VOLUME, page_sound),   // F0: not HOLD,  EXIT to volume control
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  ); //	F1: HOLD , nop

	// continue for the HOLD case only. Have to clear alternate bit (bit 1)
	ins6(nop,to_t,inc,acc_t,lit1,nop);   // get bit 1 (value 2) in T (also delay)
	ins6(nop,to_t,res,acc_t,ext_msb,bank2);  // get shape/cycle control in T (also delay), while resetting bit 1
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank2); // store new state

	ins6(nop, to_t, ld_ir, acc_t, PSG_CH_VOLUME, page_sound);  // jump to volume
	ins6(nop,to_a,xor,acc_a,lit0,nop); // nop, delay

	print_cycles();		// ~43 cycles	

	// ********************************************

	// 2-6-2025 psg_ch_volume. Starting point for a sound channel. Adjust volume for all channels,
	// then go to PSH_CH_START to process the first channel.

	opcode_page(page_sound, opc_psg_ch_volume, "PSG_CH_VOLUME", nop, nop);   //  

	// get the CH_BUF in DPL 
	ins6(nop,to_dpl,inc,acc_t,reg_snd_ch, nop);   // reg_sound_ch + 1 --> is CH_BUF
	ins6(nop,to_dph,inc,acc_t,lit4,nop);  // dph <- 5  msb of channel buffers. 

	// 1-6-2025 new section for setting the volume
	/*
	- point to CH_BUF
	- test high bit of N-TMVVVV
	- T <- volume setting N-TMVVVV, tc-to_f
	- if N active, copy T to noise-volume (including the M bit) (in ch4, N is never active, but it doesn't matter)
	- if T not active, set volume to zero, also set the M bit inactive
	- if M active, get volume from envelope
	- might increment and check zero-timer
	- get amplitude from table
	- write POS and NEG amplitudes	
    */
	ins6(tc_to_f,to_t,ld,acc_t,ext_msb,bank1);	// get amplitude, tc->F

	ins6(nop,to_a,and_tst,acc_t,lit32,nop);	// test bit T (tone)
	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop);  // tc to F
 	if_f_t(in_f(nop,to_t,ld,acc_t,lit0,nop),     // F0: bit T is 0, clear volume  
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  ); //	F1: nop
	ins6(nop,to_a,and_tst,acc_t,lit16,nop);	// test bit M (use envelope)
	// tc_to_f and then conditionally move envelope to T
	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop); // nop, tc_to_f

 	if_f_t(in_f(nop,to_t,and,acc_t,reg_0F,nop),      // 17-9-2025: only bit 0-3 (was nop)
	       in_t(nop,to_t,ld,acc_a,reg_psg_tmp,nop)  );	// F1: use envelope volume

	// new 17-9-2025, 18-9-2025  check if volume is zero. If not, set silence counter to max value.

	ins6(nop,to_a,sub,acc_t,lit1,nop); // check if T is zero
	ins6(tc_to_f,to_a,ld,acc_t,lit32,nop); // F<-tc, A <- 32

 	if_f_t(in_f(nop,to_a,ld,acc_t,lit0,nop),   // ampl was 0
	       in_t(nop,to_mem,ld,acc_a,reg_silence_cnt,nop)  );	// ampl was not 0. Set silence counter (bank1, msb) to value from A

	// 17-9-2025 end		

	// get volume from table:
	ins6(nop,to_dpl,and,acc_t,reg_0F,nop); // volume from T to dpl, only bit 0-3. 

	// 17-6-2025  have smaller volume steps 0617B
	ins6(nop,to_t,asl,acc_a,ext,bank2); // tc <- MSB (amplitude).  Bit7 of the value is actually the 'fine tuning', worth 1/2.

	ins6(tc_to_f,to_a,ld,acc_a,ext,bank2); // A <- amplitude(from table), tc->F	
	ins6(nop,to_a,res2,acc_a,reg_128,nop); // clear upper volume bit
	// place volume into CH_POL records
	ins6(nop,to_t,inc,acc_t,lit1,nop);    // T <- 2  
	ins6(nop,to_dpl,add_1,acc_t,reg_snd_ch, nop);   // T + reg_sound_ch + 1 --> is CH_POS

	//ins6(nop,to_dpl,ld,acc_t,ext,bank1);   // get first polarity record	
	ins6(nop,to_mem,ld,acc_a,ext,bank1);   // store volume
	// now complement value
 	if_f_t(in_f(nop,to_a,ld,acc_t,lit0,nop),   // A <- 0 
	       in_t(nop,to_a,dec,acc_t,lit0,nop)  );	// F1: A <- 0xFF  the negative sample becomes one step more negative

	ins6(nop,to_a,sub,acc_a,ext,bank1); // A <- A - amplitude (from the volume that was just stored)	
	// 17-6-2025 end

	ins6(nop,to_dpl,ld,acc_t,ext,bank2);   // get next polarity record CH_NEG	
	ins6(nop,to_mem,ld,acc_a,ext,bank1);   // store negative volume	
	// end volume	

	// if N bit set, copy volume to noise channel
	// get the CH_BUF in DPL 
	ins6(nop,to_dpl,inc,acc_t,reg_snd_ch, nop);   // reg_sound_ch + 1 --> is CH_BUF
	ins6(nop,to_t,asl,acc_t,ext_msb,bank1);	// get amplitude flag N (noise) to tc	
	ins6(tc_to_f,to_a,ld,acc_t,ext_msb,bank1);	// get amplitude in A, tc->F	

	ins6(nop,to_a,or,acc_a,lit32,nop); // 7-6-2025 set TONE bit

	// //get sound channel
	make_literal(to_t,0x39); // sound channel 4
	ins6(nop,to_dpl,add,acc_t,lit1,nop); // dpl <- #39+1 (CH_BUF of ch4)

	// conditionally move A to noise_volume (if N=1). This will also copy the M bit, so noise ch can also select envelope.
 	if_f_t(in_f(nop,to_t,xor,acc_t,lit0,nop),    
	       in_t(nop,to_mem,ld,acc_a,ext_msb,bank1)  );	// F1: store noise volume in ch4

	// after CH4 is totally handled, it should set its volume back to 0 (in CH_END)

	// now loop until all 4 channels were done (copied from PSG_CH_END)
	ins6(nop,to_t,ld,acc_t,reg_snd_ch,nop);  //get sound channel
	ins6(nop,to_t,add,acc_t,lit8,nop);   // select next sound channel (distance 8)

	ins6(nop,to_a,and_tst,acc_t,lit32,nop);   // when bit5 is clear, all 4 channels were done (test result to A, unused)

	ins6(tc_to_f,to_mem,ld,acc_t,reg_snd_ch,nop);  //store sound channel
	// is this the last channel ?
	// if F=0, this was the last channel	
 	if_f_t(in_f(nop,to_t,xor,acc_t,lit0,nop),    // F0: nop
	       in_t(nop, to_t, ld_ir, acc_t, PSG_CH_VOLUME, page_sound)  );  //  F1: go back to ch_volume, do next channel
		    
	// last channel was done, continue
	ins6(nop,to_t,ld,acc_t,PSG_CH_1,nop); // for the loop in psg_ch_start, set channel 1, delay
	ins6(nop,to_mem,ld,acc_t,reg_snd_ch,nop);  //store sound channel 1	

	make_literal(to_t, 0x2D); //  constant for noise generator 

    ins6(nop, to_t, ld_ir, acc_t, PSG_CH_START, page_sound); // jump to psg_ch_start
	ins6(nop,to_mem,ld,acc_t,reg_psg_tmp,nop); // save for noise generation (delay)
 	
	print_cycles();	


	// ********************************************

	// psg_ch_start. Starting point for a sound channel

	opcode_page(page_sound, opc_psg_ch_start, "PSG_CH_START", nop, nop);   //  

	// get the CH_BUF in DPL 
	ins6(nop,to_dpl,inc,acc_t,reg_snd_ch, nop);   // reg_sound_ch + 1 --> is CH_BUF
	ins6(nop,to_dph,inc,acc_t,lit4,nop);  // dph <- 5  msb of channel buffers.  searched 3 days for this... 

	// new 17-9-2025 decrement silence counter until zero. If zero, dont handle the channel.

	// since there are four channels, count will decrement 4 times at every 256 samples.
	// so initial value must be at least 16 ( 4times * 4(1K samples) ), and preferably 32 to be sure

	ins6(nop,to_t,dec,acc_a,reg_silence_cnt,nop);	// T <- dec(silence counter)
	ins6(tc_to_f,to_a,inc,acc_t,ext_msb,bank2); // F<-tc,  A <- ld inc(ch_buf_pch)

 	if_f_t(in_f(nop,to_mem,ld,acc_a,ext_msb,bank2),   // zero ! Skip filling the buffer. save incremented pch pointer
	       in_t(nop,to_mem,ld,acc_t,reg_silence_cnt,nop)  );	// non zero. Store decremented silence counter

 	if_f_t(in_f(nop,to_t,ld_ir,acc_t,PSG_CH_END,page_sound),   // zero ! jump to PSG_CH_END
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  );	// non zero. nop

	// 17-9-2025 end

	ins6(nop,to_pch,ld,acc_t,ext,bank2);      // load ch_buf_PCL
	ins6(nop,to_pch,ld,acc_t,ext_msb,bank2);  // load ch_buf_PCH
	ins6(set_c,to_a,ld,acc_t,ext_msb,bank0);  // A <- ch_buf_fraction_save, cy=1

	// 8-6-2025 check if period time is zero
	ins6(nop,to_t,inc,acc_t,lit1,nop);    // T <- 2  
	ins6(nop,to_dpl,add_1,acc_t,reg_snd_ch, nop);   // T + reg_sound_ch + 1 --> is CH_POS
	ins6(nop,to_t,ld,acc_t,ext_msb,bank0); // T <- period_msb
	ins6(nop,to_t,or_tst,acc_t,ext,bank0); // T <- T OR period_lsb

	ins6(tc_to_f,to_dpl,ld,acc_t,ext,bank2);   // get next polarity record CH_NEG, tc_to_f

 	if_f_t(in_f(nop,to_t,ld_ir,acc_t,PSG_CH_END,page_sound),    // F0: period was zero, dont handle that, go to end
	       in_t(nop,to_t,ld,acc_t,ext_msb,bank0)  );	  // F1: T <- period_msb

	ins6(nop,to_t,or_tst,acc_t,ext,bank0); // T <- T OR period_lsb  (also delay)

	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop); // tc_to_f, nop 

 	if_f_t(in_f(nop,to_t,ld_ir,acc_t,PSG_CH_END,page_sound),    // F0: period was zero, dont handle that, go to end
	       in_t(nop,to_t,xor,acc_t,lit0,nop)  );	  // F1: nop
	
	ins6(nop,to_dpl,inc,acc_t,reg_snd_ch, nop);   // reg_sound_ch + 1 --> is CH_BUF
	
	// 8-6-2025 end

	ins6(nop,to_dpl,ld,acc_t,ext,bank1); 	  // dpl <- ch_buf_pol

    ins6(c_to_f, to_t, ld_ir, acc_t, PSG_SQ_LOOP, page_sound); // jump to psg_sq_loop, set CY
	// in the delay, fill T with pcl or compl(pcl) (choosen by CY that is in F), and F <- irq
	// here since ucode0522F
 	if_f_t(in_f(irq_to_f,to_t,ld,acc_t,pcl,nop),    
	       in_t(irq_to_f,to_t,compl,acc_t,pcl,nop)  );	

	print_cycles();	

	// ********************************************	

	// psg_ch_end. End of processing for this channel. Might switch to next channel.

	opcode_page(page_sound, opc_psg_ch_end, "PSG_CH_END", nop, nop);   //  

	//ins6(nop, l_to_sw_spi_cs2_n, ld, acc_a, lit0, nop);  // CS2 low   for testing

	// channel 1-3 addresses: #21  #28  #31,  #39 (ch4, noise)  #41 (outside range, stop)
	// /* 0528D
	// 28-5-2025 scan all 4 channels
	ins6(nop,to_t,ld,acc_t,reg_snd_ch,nop);  //get sound channel
	ins6(nop,to_t,add,acc_t,lit8,nop);   // select next sound channel (distance 8)

	// normal 0530A co
	ins6(nop,to_a,and_tst,acc_t,lit32,nop);   // when bit5 is clear, all 4 channels were done (test result to A, unused)

	ins6(tc_to_f,to_mem,ld,acc_t,reg_snd_ch,nop);  //store sound channel
	// is this the last channel ?
	// if F=0, this was the last channel	
 	if_f_t(in_f(nop,to_t,xor,acc_t,lit0,nop),    // F0: nop
	       in_t(nop, to_t, ld_ir, acc_t, PSG_CH_START, page_sound)  );  //  F1: go back to start, do next channel
		   
	// last channel was done, continue

	// set the noise volume back to 0
	make_literal(to_t,0x39); // sound channel 4
	ins6(nop,to_dpl,add,acc_t,lit1,nop); // dpl <- #39+1 (CH_BUF of ch4)
	ins6(nop,to_dph,inc,acc_t,lit4,nop);  // dph <- 5  msb of channel buffers.	
	ins6(nop, to_t, ld, acc_t, lit0, nop); // clr T
	ins6(nop,to_mem,ld,acc_t,ext_msb,bank1); // store noise volume 0 in ch4

	ins6(nop, to_pch, ld, acc_t, reg_tl, nop);  // restore pcl (delay)
	ins6(nop, to_pch, ld, acc_t, reg_th, nop); 	// restore pch

	// Now restore the carry flag, to return to user program

	ins6(nop, to_dph, ld, acc_t, lit1, nop); // dph <- 1	24-6-2025 new shr

	ins6(irq_to_f, to_dpl, ld, acc_t, reg_vga_flags, nop);    // get flags to dpl

	ins6(nop, to_t, shrnew, acc_t, ext, upd_c); // do a right shift, obtain C  24-6-2025 new shr

	ins6(nop, to_t, ld, acc_t, reg_vga_lsb, nop); // get stored ISA from lsb of video line address
	ins6(nop,to_mem,ld,acc_t,reg_isa,nop);	// restore ISA

    ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // 6-10-2024 l-to_f, return to user program
	ins6(nop, to_a, ld, acc_t, reg_vga_acc, nop); //  restore accumulator
	//ins6(nop, to_a, ld, acc_t, reg_psg_acc, nop); // 1-10-2025  restore accumulator, temp test	

	print_cycles();	
	
}


//-----------------------------------------------------

//	BLITTER functions

//----------------------------------------------------


const page_blit = page_hires; // blitter page
// label values for function blocks
const INC_ALL = lit1; // newline code (all newline codes more than 16 cycles)
const opc_inc_all = 1;
const DEC_ALL = lit4; // newline code
const opc_dec_all = 4;
const INC_DST = lit33; // newline code
const opc_inc_dst = 0x21;
const FAST_INC = lit20; // newline code  25-4-2025  which opcode ?
const opc_fast_inc = 0x14;

const BLIT_DST = lit9;  // this one is very long
const opc_blit_dst = 0x09;

const BLIT_COUNTHIGH = lit40;
const opc_blit_counthigh = 0x28;

const BLIT_IRQ = lit32;
const opc_blit_irq = 0x20;

const BLIT_EXIT = lit8;
const opc_blit_exit = 0x08;

const BLIT_BSET2 = lit16;
const opc_bset2 = 0x10; // 23-3-2025


// 17-11-2024  Output ports to set parameters for the blitter

function out_blit(opc,op_name,blitter_reg)   // OUT port ,name, blitter-register
{	opcode_page(page_out, opc, op_name, nop, nop);
	if ((blitter_reg == fill_1) || (blitter_reg == fill_2))  // 30-12-2024
	  {
        // 13-3-2025  use a conversion table for the colors
		ins6(nop,to_dpl,and,acc_a,reg_0F,nop);  // take only lower 4 bits, to dpl
		ins6(nop,to_dph,inc,acc_t,lit9,nop);  // address is 0Axx. so here, load A into dph
		ins6(nop,to_t,ld,acc_t,ext,bank1);  // and load the result into T. How easy is that !
		// conversion end

		ins6(nop, to_mem, ld, acc_t, blitter_reg, nop); // write T (was ACC) to blitter register

		ins6(nop, to_dpl, or, acc_t, lit0, nop);   // dpl <- A  // 13-3 use T instead of A
		ins6(nop, to_dph, inc, acc_t, lit1, nop); // MSB of nibble swap table (0200 -02FF) in bank2
		// now dph/dpl points to the nibble-swapped ACC
		ins6(nop, to_t, ld, acc_a, ext, bank2); // T <-  swaptable(dph|dpl), bank2
		ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
		if (blitter_reg == fill_1)
		   	{ ins6(nop, to_mem, ld, acc_t, t_fill_1_sh4, nop); } // write to fill_shifted 4 bits
		else { ins6(nop, to_mem, ld, acc_t, t_fill_2_sh4, nop); } // fill_1 or fill_2

	  }
	else  
	// 11-3-2025 new. simple validity check for X, must be max 639 (27F).	
	if ((blitter_reg == size_x_h) || (blitter_reg == src_x_h) || (blitter_reg == dst_x_h))  
	  { // if (high_byte > 2) then set high byte back to 1  as emergency action.
		ins6(nop, to_dpl, shl_1, acc_a, lit1, nop); // set dpl to 3
        ins6(nop, to_t, sub, acc_a, dpl, nop); // do  T <- A - 3. must always be a negative number

		ins6(tc_to_f,to_t,xor,acc_t,lit0,nop);  		 // nop, tc_to_f. If F=1, parameter was >= 3.
		if_f_t(in_f(nop, to_t,  xor, acc_t, lit0, nop), in_t(nop, to_a, ld, acc_t, lit1, nop)); // F0: nop  F1:  A <- 1

		ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	    ins6(nop, to_mem, ld, acc_a, blitter_reg, nop); // write ACC to blitter register		
	  }
    else
	// 12-3-2025 new. simple validity check for Y, must be max 511 (1FF)
	if ((blitter_reg == size_y_h) || (blitter_reg == dst_y_h))  
	  { // if (high_byte >1) then set high byte back to 1  as emergency action.
		ins6(nop, to_dpl, inc, acc_a, lit1, nop); // set dpl to 2
        ins6(nop, to_t, sub, acc_a, dpl, nop); // do  T <- A - 2. must always be a negative number

		ins6(tc_to_f,to_t,xor,acc_t,lit0,nop);  		 // nop, tc_to_f. If F=1, parameter was >= 2.
		if_f_t(in_f(nop, to_t,  xor, acc_t, lit0, nop), in_t(nop, to_a, ld, acc_t, lit1, nop)); // F0: nop  F1:  A <- 1

		ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	    ins6(nop, to_mem, ld, acc_a, blitter_reg, nop); // write ACC to blitter register		
	  }
    else    // 11-3-2025 end
	{ ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	  ins6(nop, to_mem, ld, acc_a, blitter_reg, nop); // write ACC to blitter register	
	}
	print_cycles();
}	

// Following instruction implements the TXTGET function from SymbOs

function z80_txtget(op,name)  // 27-04-2025  ED 6C
{	opcode_page(page_z80_ed, op, name, nop, nop); 
	// input:
	// IX: txtget+1  number of chars to print in string
	// IY: pointer to character string
	// BC: font base
	// alt-ACC  Y-clipping
	// output:
	// t_dp_msb/lsb font addr of character
	// A  Zeichenbreite. 
	// output CY=1: OK, CY=0: stop

	ins6_chi(nop, to_t, ld, nop, reg_ixl, nop);
	ins6_pcmin2(nop, to_t, or_tst, acc_t, reg_ixh, upd_c);  // check if there are chars to print
	ins6(tc_to_f, to_a, ld, acc_t, lit0, nop);	 // for returning A=0 (unused, now use cy)
	//  F0: was zero, exit cy=0   F1: ld charpt lsb
	if_f_t(in_f(irq_to_f, to_t, ld_ir, acc_t, pc_pp, nop), in_t(nop, to_dpl, ld, acc_t, reg_iyl, nop));	

	ins6(nop, to_dph, ld, acc_t, reg_iyh, nop); // ld charpt msb  (also delay)

	ins6(nop, to_t, dec, nop, reg_ixl, nop); //  decrement IX lsb
	ins6(nop, to_mem, ld, acc_t, reg_ixl, nop);
	ins6(nop, to_t, dec_dtc, acc_t, reg_ixh, nop); //  decrement IX msb
	ins6(nop, to_mem, ld, acc_t, reg_ixh, nop);

	ins6(nop, to_t, dec, acc_t, ext, upd_c); // load decrement char to check if zero
	ins6(tc_to_f, to_dpl, ld, acc_t, ext, nop);  // load char to dpl

	//  F0: was zero, exit cy=0   F1: dpl shift left
	if_f_t(in_f(irq_to_f, to_t, ld_ir, acc_t, pc_pp, nop), in_t(nop, to_dpl, asl, acc_t, dpl, nop));	

	ins6(nop, to_t, rol_tc, acc_t, lit0, nop);  // T <- (0 << 1) + tc  (also delay instruction)
	ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop);  // store T temporary at reg_vga_acc  27-9-2025 to_mem instead of to_t

	// the character was now shifted left, one position, into <t><dpl>.  Repeat this 3 times

	ins6(nop, to_dpl, asl, acc_t, dpl, nop)
	ins6(nop, to_t, rol_tc, acc_t, reg_vga_acc, nop);  // T <- (0 << 1) + tc
	ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop);  // store T  27-9-2025 to_mem instead of to_t

	ins6(nop, to_dpl, asl, acc_t, dpl, nop)
	ins6(nop, to_t, rol_tc, acc_t, reg_vga_acc, nop);  // T <- (0 << 1) + tc
	ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop);  // store T  27-9-2025 to_mem instead of to_t

	ins6(nop, to_a, asl, acc_t, dpl, nop)   // for last shift, lsb destination A
	ins6(nop, to_t, rol_tc, acc_t, reg_vga_acc, nop);  // T <- (0 << 1) + tc
	//ins6(nop, to_t, ld, acc_t, reg_vga_acc, nop);  // store T  last shift doesnt need store
	// now the char is shifted 4 times to the left. Add the base addr of the character font (is in BC)

	ins6(nop, to_a, add, acc_a, reg_c, nop); // add font lsb
	ins6(nop, to_t, add_tc, acc_t, reg_b, nop); // add font msb

	ins6(nop, to_dpl, add, acc_a, lit0, nop); // dpl <- A
	ins6(nop, to_dph, add, acc_t, lit0, nop); // dph <- T	
    // now, dph/dpl can be used to fetch Zeichenbreite
	// now add Y-clipping (where does that come from ?)

	ins6(nop, to_a, add, acc_a, reg_a_alt, nop); // add y-clipping from alternate accumulator
	ins6(nop, to_t, add_tc, acc_t, lit0, nop);    // handle cy

	ins6(nop, to_mem, ld, acc_a, t_dp_lsb, set_c); // font addr of the character: lsb  CY=1 (success)
	ins6(nop, to_mem, ld, acc_t, t_dp_msb, nop);    // msb 

	ins6(nop, to_a, ld, acc_t, ext, nop); // Zeichenbreite to ACC

	ins6(nop, to_t, inc, acc_t, ext, nop);    // get incremented Zeichenbreite
	ins6(nop, to_t, add, acc_t, lit32, nop);  // add 0x20
	ins6(nop, to_dpl, res2, acc_t, lit1, nop); // reset bit0, result to dpl (Zeichenbreite rounded-up to even value)
	ins6(nop, to_t, asl, acc_t, dpl, nop);   // the result is left-shifted, result in T

	final(irq_to_f, to_mem, ld, acc_t, t_label1, nop); // store result at label1, for ROWSEL instruction

	print_cycles(); 
}


function z80_rowsel(op,name)  // 28-4-2025 row select. jumps to the txtrow instruction who's address is in t_label1
{	opcode_page(page_z80_ed, op, name, nop, nop);   // this is on the ED page, ED 5C

	ins6(nop, to_t, ld_ir, acc_a, t_label1, page_blit); // The label1 value was calculated in the TXTGET function
	ins6(nop, to_dpl, ld, acc_a, t_dp_lsb, nop); // dpl <- t_dp_lsb  // get addr of pixel row from font

	print_cycles(); // 33 cycles
}

// 28-4-2025  function to produce one row of pixels for a character. Max 8 pixels on a row.
// there are several of these, each for a different number of pixels on the row.


// 27-9-2025 re-enabled TXTROW
// values of 2, 4, 6 and 8 pixels are supported. So txtrow 2, txtrow 4, txtrow 6, txtrow 8. 1-5 txrow 0 added.
// Opcode is optained by shifting the value right (one step), and add 0x40. So opcodes 0x44, 0x48, 0x4C, 0x50.
function txtrow(op,name)
{	opcode_page(page_blit, op, name, nop, nop);   // these are on the blitter page

	var pixels = (( op - 0x40) >> 1 ) & 0x0F;
	var counter = pixels >> 1; 
	var unaligned = 0; // 29-4-2025A   have to find out when to set it to 1
	// ins6(nop, to_dpl, ld, acc_a, t_dp_lsb, nop); // dpl <- t_dp_lsb  // get addr of pixel row from font (moved to rowsel)
	ins6(nop, to_dph, ld, acc_t, t_dp_msb, nop); // dph <- t_dp_msb

	ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop); // dpl <- (dph/dpl)  get pixel row

	// save program counter and load it from DE (buffer destination)
	ins6_chi(nop,to_t,ld,acc_t,pcl,nop);  // pcl
	ins6_pcmin2(nop,to_mem,ld,acc_t,t_temp_pcl,nop); // pcl
	ins6(nop,to_pch,ld,acc_t,reg_e,nop); // write new pcl
	ins6(nop,to_t,ld,acc_t,pcl,nop);  // pch
	ins6(nop,to_mem,ld,acc_t,t_temp_pch,nop); // pch
	ins6(tc_to_f,to_pch,ld,acc_t,reg_d,nop); // write new pch	

	// function main action section

	// 29-4-2025A: section to be executed for unaligned. 
	if (unaligned==1) // 29-4-2025A
	   {  ins6(nop,to_dpl,asl,acc_t,dpl,nop); // dpl <- asl(dpl)
		  ins6(tc_to_f,to_t,ld,acc_t,pc,nop); // get the two pixels, only the low nibble will change
	      ins6(nop,to_t,res2,acc_t,reg_0F,nop); // clear lower nibble
		  if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0: pix6, BG  F1: pix6, FG
		  ins6(nop, to_mem, ld, acc_t, pc_pp, nop);  // store the two pixels		  
	   }

	// from: aligned TEXT blitter function
	
		var i=counter;  // counter is 4,3,2 or 1.   pixels 7,6 and 5,4 and 3,2 and 1,0.
		while (i != 0)
		{	
			ins6(nop,to_dpl,asl,acc_t,dpl,nop); // dpl <- asl(dpl)
			no_f_write_error = 1;			
			ins6(tc_to_f,to_dpl,asl,acc_t,dpl,nop) ;  // dpl <- asl(dpl), tc_to_f
			no_f_write_error = 0;

			if_f_t(in_f(tc_to_f, to_t, ld, acc_t, t_fill_2_sh4,nop ), in_t(tc_to_f,to_t,ld,acc_t,t_fill_1_sh4,nop) );   //   F0: pix7, BG  F1: pix7, FG
			if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0: pix6, BG  F1: pix6, FG

			ins6(nop, to_mem, ld, acc_t, pc_pp, nop);  // store the two pixels
			i = i-1;
		}

	// end of main action section

	ins6(nop,to_pch,ld,acc_t,t_temp_pcl,nop); // restore pcl of program code
	ins6(nop,to_pch,ld,acc_t,t_temp_pch,nop); // restore pch of program code	

	// now double-inc D, point to next row of buffer. Rows are 512 bytes apart
	ins6(nop, to_t, inc, acc_t, reg_d, nop);        // T <- reg_d + 1
	ins6(nop, to_t, add, acc_t, lit1, nop);	        // T <_ T + 1 
	ins6(nop, to_mem, ld, acc_t, reg_d, nop);       // reg_d <- T

	// now inc t_dp_msb/lsb, point to next row of pixels in the font
	ins6(nop, to_t, inc, acc_t, t_dp_lsb, nop);		    // lsb
	ins6(irq_to_f, to_mem, ld, acc_t, t_dp_lsb, nop);      // 
	ins6(nop, to_t, inc_dtc, acc_t, t_dp_msb, nop);   // T msb
	final(nop, to_mem, ld, acc_t, t_dp_msb, nop);          // 
	print_cycles(); // 
}

function col4to16(op,name)  // convert 4-color to 16-color  4-5-2025
{	opcode_page(page_z80_ed, op, name, nop, nop);  
// COL4TO16   ED 54
// At the start, the msb of conversion table must be in C.
//  LD T,(de)
	ins6(nop,to_dpl,ld, acc_t,reg_e,nop); // DPL <- reg_e  // address of 4 pixels
	ins6(nop,to_dph,ld, acc_t,reg_d,nop); // DPH <- reg_d

	ins6(nop, to_dpl, asl, acc_t, ext, nop); //   dpl <- (dph/dpl) << 1  ; load and shift
	ins6(nop, to_dph, inc_tc, acc_t, reg_c, nop); // msb of table: dph <- reg_c + cy

	ins6(nop, to_a, ld, acc_t, ext, nop); // get first two pixels from table in A
	ins6(nop, to_t, ld, acc_t, ext_msb, nop); // get second two pixels from table in T

	ins6(nop,to_dpl,ld, acc_t,reg_l,nop); // DPL <- reg_l  // destination address
	ins6(nop,to_dph,ld, acc_t,reg_h,nop); // DPH <- reg_th

	ins6(nop, to_mem, ld, acc_a, ext, nop); // store first two pixels from table 
	ins6(nop, to_mem, ld, acc_t, ext_msb, nop); // store second two pixels from table

    // now inc HL by 2
	ins6(nop, to_t, inc, acc_t, reg_l, nop);		   // T <- reg_l +1
	ins6(nop, to_t, add, acc_t, lit1, nop);	       // this assumes HL is even !
	ins6(nop, to_mem, ld, acc_t, reg_l, nop);          // reg_l <- T
	ins6(nop, to_t, inc_dtc, acc_t, reg_h, nop);       // T reg_h + 1 (if there was a cy)
	ins6(irq_to_f, to_mem, ld, acc_t, reg_h, nop);     // reg_h <- T
  
	// inc DE
    ins6(nop, to_t, inc, acc_t, reg_e, nop);		   // T <- reg_e +1
	ins6(nop, to_mem, ld, acc_t, reg_e, nop);          // reg_e <- T
	ins6(nop, to_t, inc_dtc, acc_t, reg_d, nop);       // T reg_d + 1 (if there was a cy)
	final(irq_to_f, to_mem, ld, acc_t, reg_d, nop);     // reg_d <- T
	print_cycles(); // 
}	


/* 11-1-2025 New Blitter action codes

D_BMCOPY is now #08. D_BMCOPYCNV is #00 (copy and convert color)  (re-inserted 26-3-2025 )

D_BMCOPY equ #00 ; was also #0      B_C  BUC    B_LC  B_CR  BUCR  B_PC (prepare copy)
D_BMSAVE equ #01 ; new      B_V
;            #02 ; COPY + BLITP24   B_2
;            #03 ; free
;            #04 ; free 
D_BMSKIP equ #04 ; was #28  B_S   SKIP also converts color
;            #06 ; SKIP + BLITP24   B_M (M for Mousepointer...)
D_BMTEXT equ #09 ; was #30. B_T

; The 0x20 in the fill codes disable source calculation
D_BMFILL equ #2D ; bit3=1 disables src calculation (X8, X9 kept free).  B_F
D_BMFXOR equ #2E ; bit3=1 disables src calculation  B_X

The following modifier codes can be added to the action code:

D_BLITBACKX equ #0B ; Only for COPY. Action is performed right-to-left. (not yet possible)  B_R
D_BLITBACKY equ #80 ; Only for COPY. Action is performed bottom-to-top. (not yet possible)

D_BLITP14 equ #00 ; Only used with TEXT. Converts 1bpp to 4 bpp (bits per pixel)
D_BLITP24 equ #02 ; Only used with COPY or SKIP. Converts 2bpp to 4 bpp
D_BLITP44 equ #00 ; Default, screen and source are both 4bpp
*/

// 22-11-2024 Output port that starts the blitter action: port_blitter. Action code in ACC.

function out_blit_start(opc,op_name)   // OUT port ,name, 
{	opcode_page(page_out, opc, op_name, nop, nop);

 	ins6(nop, to_mem, ld, acc_a, reg_vga_acc, nop); // save Accumulator

	// new section 9-3-2025 check for zero size in x or y direction
	ins6(nop,to_t,ld,acc_t,size_x_l,nop);
	ins6(nop,to_dpl,or,acc_t,size_x_h,nop);
	ins6(nop, to_dpl, dec, acc_t, dpl, nop); // add FF to check for zero, TC=0 if zero
	ins6(tc_to_f,to_t,ld,acc_t,size_y_l,nop);  // tc to F, take Y-low

	if_f_t(in_f(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset), in_t(nop,to_dpl,or,acc_t,size_y_h,nop));	 // F=0 exit   F=1 or with Y-high
	
	ins6(nop, to_dpl, dec, acc_t, dpl, nop); // add FF to check for zero, TC=0 if zero
	ins6(tc_to_f,to_t,ld,acc_t,lit0,nop);  // tc to F, nop	 
	if_f_t(in_f(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset), in_t(nop,to_t,ld,acc_t,lit0,nop));	 // F=0 exit   F=1  nop
	// end 9-3-2025 section

	// 25-4-2025 new
	ins6(nop, to_dpl, asl, acc_t, src_a_u, nop); // screen addr is 0x800000  . dpl result unused.	
	
	ins6(tc_to_f, to_t, ld, acc_t, reg_isa, nop); // get current ISA, tc to F
	ins6(nop, to_mem, ld, acc_t, t_temp_reg_isa, nop); // store at temp.

	ins6(nop, to_t, add, acc_a, reg_128, nop); // move upper bit of action to tc. If 1, indicates backwards Y
	// Action code is in ACC.

    // F=0   source=mem                      F=1  source = screen, test for bank change
	if_f_t(in_f(tc_to_f, to_t, ld, acc_t, FAST_INC, nop), in_t(tc_to_f, to_t, ld, acc_t, INC_ALL, nop));

    // F=0   normal, inc line nr INC_ALL or FAST_INC      F=1  backwards Y  decrement line nr each iteration
	if_f_t(in_f(nop, to_t, xor, acc_t, lit0, nop), in_t(nop, to_t, ld, acc_t, DEC_ALL, nop));
	ins6(nop, to_mem, ld, acc_t, t_label5, nop); // store at label 5

	// 25-4-2025 end


	ins6(nop, to_a, or, acc_a, reg_128, nop); // set bit 7 in actioncode
	ins6(nop, to_mem, ld, acc_a, t_save_dpl, nop); // temp save action code at t_save_dpl

	ins6(nop, to_t, dec, acc_t, lit0, nop); // t <- 0xFF
	ins6(nop, to_mem, ld, acc_t, t_save_t, nop); // 25-11-2024 preset bank register to FF (appl=1) in case no source present

	commentline("--- start source calculation. Check if aligned or not ---");
	// check if start addr of src and dst are different (lowest bit)
	ins6(nop, to_t, ld, acc_t, dst_x_l, nop);
	ins6(nop, to_t, xor, acc_t, src_x_l, nop);	
	ins6(nop, to_t, and, acc_t, lit1, nop);	 // select bit 0
	ins6(nop, to_t, sub, acc_t, lit1, nop);	// dec T,gives tc=1 if bit0 was set	
	//ins6(tc_to_f, to_a, xor, acc_a, lit4, nop); // tc to F	. Action still in ACC, set bit 4 (but use xor)
	ins6(tc_to_f, to_a, xor, acc_a, lit16, nop); // tc to F	. Action still in ACC, set bit 4 (but use xor). 30-1-2025, use lit16 !	

    // F=0   bit3=0, do source calc        F=1  bits unequal, set action = action OR 0x10 (unaligned)
	if_f_t(in_f(nop, to_t, ld, acc_t, lit0, nop), in_t(nop, to_mem, ld, acc_a, t_save_dpl, nop));	// F0: nop, F1: set UNALIGNED code

    // 30-1-2025 moved skip section to here. Strange, it didnt help.
	commentline("--- check if source calculation can be skipped ---");
	// check if we can skip the source calculation. That is the case for FILL and FXOR codes.
	//ins6(nop, to_t, and, acc_a, lit8, nop); // check bit3
	ins6(nop, to_t, and, acc_a, lit32, nop); // 11-1-2025 check bit5
	ins6(nop, to_t, sub, acc_t, lit1, nop);	// dec T,gives tc=1 if bit3 was set
	ins6(tc_to_f, to_t, ld, acc_t, lit0, nop); // nop, tc to F

    // F=0   bit3=0, do source calc        F=1  bit3=1, no source calc. goto dst calc

	// 7-4-2025A
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_t, ld, acc_t, INC_DST, nop));	

	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_t, ld_ir, acc_t, BLIT_DST, page_blit));	// 23-12-2024	
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_mem, ld, acc_t, t_label5, nop)); // delay

	// end of moved section

	commentline("--- source calculation X, check irq ---");
	// calc source X
	ins6(nop,to_dph,ld,acc_t,lit1,nop); // 30-6-2025 for shr

	ins6(irq_to_f, to_dpl, ld, acc_t, src_x_h, nop); // dpl <- src_x_h , also delay
	ins6_chi(nop, to_t, shrnew, acc_t, ext, upd_c); // T <- shr(dpl), wr cy  30-6-2025 shrnew

    // F=0   interrupt, restore A       F=1  no interrupt
	if_f_t(in_f(nop, to_a, ld, acc_t, reg_vga_acc, nop), in_t(nop,to_t,xor,acc_t,lit0,nop));	// F0: restore A, F1: delay, c_to_f can not immediately follow upd_c

	ins6(c_to_f, to_dpl, ld, acc_t, src_x_l, nop); // dpl <- src_x_l, f <- cy

	ins6(nop, to_a, shrnew, acc_a, ext, upd_c); // T <- shr(dpl), wr cy. Cy tells if number was odd. But we already handled that. 30-6-2025 shrnew	 

	// move the bit that was shifted out the high byte into the low byte
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_a, or, acc_a, reg_128, nop));

	ins6(nop, to_mem, ld, acc_a, t_dp_lsb, nop); // store lower at t_dp_lsb
	ins6(nop, to_mem, ld, acc_t, t_dp_msb, nop); // store upper at t_dp_msb
	commentline("--- source calculation Y. Multiply by 320 ---");
	// calc source Y
	// The Y coordinate will be multiplied by 320. Thats the length used by the screen.
	// For other lengths, we simply suppose that Y is always 0, so multiplication with 320 also yields 0.

	ins6(nop, to_t, dec, acc_t, src_y_h, nop); // bit0 of src_x_h  to TC (T unused)
	ins6(tc_to_f, to_dpl, ld, acc_t, src_y_l, nop); // dpl <- src_y_l, F <- tc

	ins6(nop, to_a, shrnew, acc_t, ext, upd_c); // lowest bit to cy	30-6-2025
	if_f_t(in_f(nop, to_dpl, or, acc_a, lit0, nop), in_t(nop, to_dpl, or, acc_a, reg_128, nop)); // upper bit shifted in
	ins6(c_to_f, to_dpl, ld, acc_t, dpl, nop); // nop, cy->f
	ins6(nop, to_a, shrnew, acc_t, ext, upd_c); // again shr, prev cy to F	30-6-2025
	if_f_t(in_f(nop, to_t, ld, acc_t, lit0, nop), in_t(nop, to_t, asl, acc_a, lit32, nop)); // Cy goes to bit6 in T

	ins6(c_to_f, to_t, xor, acc_t, lit0, nop); // nop, cy to F
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_t, or, acc_t, reg_128, nop)); // Cy goes to bit 7 in T

	ins6(nop, to_a, add, acc_a, src_y_l, nop); // add MSB's, cy in tc
	ins6(nop, to_dpl, inc_tc, acc_t, src_y_h, nop); // usb to dpl (only one bit)
    // multiplication end. Now add base address. For screen, base addr must be 0x0600 (change in OS)
	commentline("--- end multiply. Now add base addr ---");
	// result of prev step: <DPL><A><T>
	ins6(nop, to_t, add, acc_t, src_a_l, nop); // add base addr lsb
	ins6(nop, to_mem, ld, acc_t, t_count_msb, nop); // save result temporary at t_count_msb
	ins6(nop, to_a, add_dtc, acc_a, src_a_h, nop); // add base addr msb

	ins6(nop, to_t, inc_tc, acc_t, dpl, nop); // handle cy, add it to top bit of addr
    // base addr has been added now.

	ins6(nop, to_t, sub, acc_t, lit1, nop);	// dec T,gives tc=1 if upper was set
	ins6(tc_to_f, to_t, xor, acc_t, lit0, nop); // nop, tc->f
	// if F=1, it is a screen address in the second 64K section.
	// add 0x0600 to address, so add 0x06 to msb (that is in acc)
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_a, add_1, acc_a, lit1, nop)); // F1: add 2
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_a, add, acc_a, lit4, nop)); // F1: add 4
	// result: <A><t_count_msb> (and F set if 2nd 64k in screen is selected)
	commentline("--- source calculation, set bank number, check irq ---");
	/* 19-11-2025 removed
    // now set bank number
	ins6(nop, to_t, asl, acc_t, lit32, nop); // set bit 6 in T
	ins6(nop, to_t, or, acc_t, reg_128, nop); // T <- T or 128. Now T = 11000000.
	// 17-11-2025 remove nxt line, A19 must not be changed. 1117C re-inserted
	ins6(nop, to_t, or, acc_t, lit8, nop); // set bit3.  Now T = 11001000. Might be reset by a SUB but will be set again lateron. 1-1-2025.

	ins6(nop, to_t, or, acc_t, src_a_u, nop); // T <- T or addr_upper. addr_upper = x0000xxx

	// for 2nd 64k screen section, add 2 to bank number (in T): 
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_t, add_1, acc_t, lit1, nop)); // F1: add 2
	
	// now take upper addr bit to see if it is screen or memory. Put it in tc.
	ins6(nop, to_dpl, asl, acc_t, src_a_u, nop); // screen addr is 0x800000  . dpl result unused.
	ins6(tc_to_f, to_t, xor, acc_t, lit0, nop); // nop, tc->f
	// F=0:  memory                 F=1: screen
	if_f_t(in_f(nop, to_t, sub, acc_t, lit1, nop), in_t(nop, to_t, or, acc_t, lit0, nop)); // F0: T <- dec(T)
	if_f_t(in_f(irq_to_f, to_t, xor, acc_t, lit4, nop), in_t(irq_to_f, to_t, xor, acc_t, lit0, nop)); // F0: T <- T xor 4

	// ins6(nop, to_t, or, acc_t, lit8, nop); // set bit3. Makes bank-decrement circular. 17-11-2025 removed, for A19=0
	ins6(nop, to_t, res2, acc_t, lit8, nop); // 17-11-2025 reset bit3. ucode1117C
	*/
	// 19-11-2025 new
	ins6(nop, to_t, ld, acc_t, reg_128, nop); // T <- 128. 
	ins6(nop, to_dpl, or, acc_t, lit8, nop); // DPL <- T or bit3. A = 10001000	

	ins6(nop, to_t, asl, acc_t, lit32, nop); // set bit 6 in T
	ins6(nop, to_t, or, acc_t, src_a_u, nop); // T <- T or addr_upper. addr_upper = x000NBBB, result x100NBBB

	// for 2nd 64k screen section, add 2 to bank number (in T): 
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_t, add_1, acc_t, lit1, nop)); // F1: add 2

	//ins6(nop, to_t, res2, acc_t, lit8, nop)	; // test if this is the problem (ucode1120H)

	ins6(nop, to_dpl, and_tst, acc_t, dpl, nop); // test if bit7 or bit3 is set, result in tc
	ins6(tc_to_f, to_t, xor, acc_t, lit0, nop); // nop, tc-> F
	//ins6(l_to_f, to_t, xor, acc_t, lit0, nop); // nop, l-> F	for testing

	// F=0  (lower 512k)   F=1: upper 512k, or screen
	if_f_t(in_f(nop, to_t, add_1, acc_t, lit1, nop), in_t(nop, to_t, xor, acc_t, lit0, nop)); // F0: T <- T + 2   F1: nop
	if_f_t(in_f(nop, to_t, add, acc_t, lit1, nop), in_t(nop, to_t, xor, acc_t, lit0, nop)); // F0: T <- T + 1   F1: nop

	if_f_t(in_f(irq_to_f, to_t, res2, acc_t, lit8, nop), in_t(irq_to_f, to_t, xor, acc_t, lit0, nop));// F0: reset bit3 in T  F1: nop
	// note that bit7 of the result is undefined


	// end new 

	// 25-11-2024 not write only to BNK register. first put in t_save_t.
	ins6_chi(nop, to_mem, ld, acc_t, t_save_t, nop); // check interrupt. write T to bank register. Have to use ADD.

    // 9-3-2025 do not write reg_bnk_dp here. Is done later with byte stored in t_save_t
	if_f_t(in_f(nop, to_a, ld, acc_t, reg_vga_acc, nop), in_t(nop, to_t, xor, acc_t, lit0, nop)); // F0: restore A  F1: NOP

	// the bank number has been set now (9-3-2025 will be done later)
	// address in <A><t_count_msb>
	commentline("--- source, add X coordinate offset ---");
	// now add the X-coordinate offset to the line start address

	ins6(nop, to_t, ld, acc_t, t_count_msb, nop); // get lsb. t_count_msb can now get other use.
	ins6(nop, to_t, add, acc_t, t_dp_lsb, nop); // add lsb
	ins6(nop, to_mem, ld, acc_t, t_dp_lsb, nop); // store
	ins6(nop, to_t, add_dtc, acc_a, t_dp_msb, nop); // add msb
	ins6(nop, to_mem, ld, acc_t, t_dp_msb, nop); // store
	commentline("--- end source calculation. Goto dest calculation ---");
	ins6(nop, to_t, ld_ir, acc_t, BLIT_DST, page_blit); // jp to dst calc
	ins6(nop, to_t, or, acc_t, lit0, nop); // nop, delay
	print_cycles();  // 64 cycles !


	// Now calculate DESTINATION (screen)  BLIT_DST


	opcode_page(page_blit, opc_blit_dst, "BLIT_DST", nop, nop); // opcode 0x09
	
	commentline("--- destination calculation X, check if: dst_x + size_x <= 640 ---");	
    // value 640 is 0x280

    // could the size become zero ??

	// Address calculation is almost the same as for source.
	commentline("--- destination calculation X, check irq ---");

	ins6(nop,to_dph,ld,acc_t,lit1,nop); // 30-6-2025 shr
	// calc dst X
	ins6(irq_to_f, to_dpl, ld, acc_t, dst_x_h, nop); // dpl <- dst_x_h 

	ins6_chi(nop, to_t, shrnew, acc_t, ext, upd_c); // T <- shr(dpl), wr cy 30-6-2025

	// 27-12-2024
	if_f_t(in_f(nop, to_a, ld, acc_t, reg_vga_acc, nop), in_t(nop, to_dpl, ld, acc_t, dst_x_l, nop)); // F0: restore A (for CHI), F1:  dpl <- dst_x_l, f <- cy
	ins6(c_to_f, to_t, xor, acc_t, lit0, nop);
	ins6(nop, to_a, shrnew, acc_a, ext, upd_c); // T <- shr(dpl), wr cy. Cy tells if number was odd. will be handled separately. 30-6-2025	

	// move the bit that was shifted out the high byte into the low byte
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_a, or, acc_a, reg_128, nop));

	ins6(nop, to_mem, ld, acc_a, t_pc_lsb, nop); // store lower at t_pc_lsb
	ins6(nop, to_mem, ld, acc_t, t_pc_msb, nop); // store upper at t_pc_msb
	commentline("--- destination calculation Y. Multiply by 320 ---");
	// calc dst Y. Y coordinate from 0 - 399.
	// The Y coordinate will be multiplied by 320. Thats the length used by the screen.
	// Other lengths are not used for the screen.

	ins6(nop, to_t, dec, acc_t, dst_y_h, nop); // bit0 of dst_x_l  to TC (T unused)
	ins6(tc_to_f, to_dpl, ld, acc_t, dst_y_l, nop); // dpl <- dst_y_l, F <- tc

	ins6(nop, to_a, shrnew, acc_t, ext, upd_c); // lowest bit to cy  30-6-2025

	if_f_t(in_f(nop, to_dpl, or, acc_a, lit0, nop), in_t(nop, to_dpl, or, acc_a, reg_128, nop)); // upper bit shifted in
	
	ins6(c_to_f, to_dpl, ld, acc_t, dpl, nop); // nop, cy->f (use dpl to get R0 for next shr)
	
	ins6(nop, to_a, shrnew, acc_t, ext, upd_c); // again shr, prev cy to F	30-6-2025
	if_f_t(in_f(nop, to_t, ld, acc_t, lit0, nop), in_t(nop, to_t, asl, acc_a, lit32, nop)); // Cy goes to bit6 in T

	ins6(c_to_f, to_t, xor, acc_t, lit0, nop); // nop, cy to F
	if_f_t(in_f(irq_to_f, to_dpl, xor, acc_t, lit0, nop), in_t(irq_to_f, to_dpl, xor, acc_t, reg_128, nop)); // Cy goes to bit7 in T

	ins6(nop, to_a, add, acc_a, dst_y_l, nop); // add MSB's, cy in tc
	ins6(nop, to_t, inc_tc, acc_t, dst_y_h, nop); // usb to t (only one bit)
	// multiplication result: <T><A><DPL>  This is a 128k range, upper bit (in T) can only be 0 or 1
    // multiplication end. Now add base address. base addr must be 0x0600 (change in OS)
	commentline("--- end multiply. Now add screen base addr, always 0x0600. check irq ---");
 	ins6(nop, to_a, add_1, acc_a, lit1, nop); //  add 2
	ins6(nop, to_t, add_tc, acc_t, lit0, nop); // handle cy, add it to top bit of addr that is in T

	ins6_chi(nop, to_a, add, acc_a, lit4, nop);  //  add 4

	if_f_t(in_f(nop, to_a, ld, acc_t, reg_vga_acc, nop), in_t(nop, to_t, add_tc, acc_t, lit0, nop)); // F0: restore A F1: handle cy, add it to top bit of addr

    // base addr has been added now.
	commentline("--- destination calculation, set bank number ---");
	ins6(nop, to_t, sub, acc_t, lit1, nop);	// dec T,gives tc=1 if upper was set

	ins6(tc_to_f, tc_to_sw_pc17, ld, acc_t, lit0, nop); //  tc->f, and tc to bit17 of PC
	ins6(nop, l_to_sw_pc18, ld, acc_t, lit0, nop);	 // 24-12-2024  set PC18 low
	ins6(nop, l_to_sw_pc19, ld, acc_t, lit0, nop);	 // 23-1-2026  set PC19 low	
	// Now PC bank has been changed, interrupt with ins6_chi must no longer be used.

	ins6(nop,to_t,ld,acc_t,lit16, nop); // T <-16   23-2-2025 disable interrupt
    ins6(nop,to_t,res,acc_t,reg_irq, nop);    // T <- T res reg_irq (reset bit T in reg_irq)
	ins6(nop,to_mem,ld,acc_t,reg_irq, nop);	

	// if F=1, destination is a screen address in the second 64K section.
	// add 0x0600 to address, so add 0x06 to msb (that is in acc)
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_a, add_1, acc_a, lit1, nop)); // F1: add 2
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_a, add, acc_a, lit4, nop)); // F1: add 4	

	// 25-11-2024 set source bank number here, if source not used, will set appl=1 (with value FF)
	ins6(nop, to_bnk, ld, acc_a, t_save_t, nop);	

    // 25-2-2025 also put it in the shadow register
	ins6(nop, to_t, ld, acc_t, t_save_t, nop);	 
    ins6(nop, to_mem, ld, acc_t, reg_bank_dp, nop);	 // store a copy of the bankswitch value		
    // 25-2-2025 end

	commentline("--- destination, add X coordinate offset ---");
	// now add the X-coordinate offset to the line start address

	ins6(nop, to_t, ld, acc_t, t_pc_lsb, nop); // get lsb. 
	ins6(nop, to_t, add, acc_t, dpl, nop); // add lsb
	ins6(nop, to_mem, ld, acc_t, t_pc_lsb, nop); // store

	ins6(nop, to_t, add_dtc, acc_a, t_pc_msb, nop); // add msb // 27-12-2024 change acc_t to acc_a
	ins6(nop, to_mem, ld, acc_t, t_pc_msb, nop); // store
	commentline("--- end destination calculation ---");

	commentline("--- size X calculation ---");
	// calc size X, divide the input size by 2 to get byte count
	ins6(nop,to_dph,ld,acc_t,lit1,nop); // 30-6-2025 shr (needed since BNK was written, modifying DPH)

	ins6(nop, to_dpl, ld, acc_t, size_x_h, nop); // dpl <- size_x_h 
	ins6(nop, to_t, shrnew, acc_t, ext, upd_c); // T <- shr(dpl), wr cy 30-6-2025	
	ins6(nop,to_t,xor,acc_t,lit0,nop);  // distance between upd_c and c_to_f

	ins6(c_to_f, to_dpl, ld, acc_t, size_x_l, nop); //   dpl <- size_x_l, f <- cy

	ins6(nop, to_a, shrnew, acc_a, ext, nop); // A <- shr(dpl).  16-3-2025 CY could be written, but it's not used.	30-6-2025 shr

	// move the bit that was shifted out of the high byte into the low byte
	if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_a, or, acc_a, reg_128, nop));

	// the shifted count is now in <T><A>

	ins6(nop, to_mem, ld, acc_t, t_bytecount_msb, nop); // store T (upper) at t_bytecount_msb

	// when an extra pixel is handled at beginning AND at the end, we need the loop to be one iteration less
	// That is the case when destination is odd and length is even.

	ins6(nop, to_t, inc, acc_t,dst_x_l,nop); // T <- dst, invert bit0
	ins6(nop, to_t, or, acc_t,size_x_l,nop); // T <- T or size. Result in bit0 is only 0 when dst odd and length even.
	ins6(nop, to_t, and, acc_t, lit1, nop);	 // select bit 0
	ins6(nop, to_t, sub, acc_t, lit1, nop);	// dec T,gives tc=1 if bit0 was set	

	ins6(tc_to_f, to_mem, ld, acc_a, t_bytecount, nop); // store A (lower) at t_bytecount, tc -> F

	ins6(nop,to_a,sub,acc_a,lit1,nop); // A <- A - 1
	ins6(nop,to_t,dec_tc,acc_t,t_bytecount_msb,nop); // conditionally decrement high byte

    // 16-2-2025 condition must be reversed ? No, it seems ok.
	if_f_t(in_f(nop, to_mem, ld, acc_a, t_bytecount, nop), in_t(nop, to_a, or, acc_a, lit0, nop)); // F0: store A at t_bytecount
	if_f_t(in_f(nop, to_mem, ld, acc_t, t_bytecount_msb, nop), in_t(nop, to_a, or, acc_a, lit0, nop)); // F0: store T at t_bytecount_msb

    // new section 25-1-2025. If bytecount_msb==1, add one to bytecount, because msb==1 represents only 255 counts and not 256.
	// 16-3-2025 remove for test. But didnt help.
	ins6(nop, to_t, dec, acc_t,t_bytecount_msb,nop); // if tc=1, bytecount_msb was 1
    ins6(nop, to_t, inc_tc, acc_a, t_bytecount, nop); // T <- bytecount + tc
	ins6(nop, to_mem, ld, acc_t, t_bytecount, nop); // store bytecount


	commentline("--- main blitter loop setup ---");

	// The main, two-dimensional loop is organized as several action blocks:

	// LBL1: First block is either "loop_prepare" or "first correction" aka left correction
	// at the end, jumps to t_label2

	// LBL2: Second block is "loop". It is not always executed.
	// at the end, jumps to t_label3. Within loop, an interrupt can be handled.

	// LBL3: Third block is "counter high bit" BLIT_COUNTHIGH. It is not always executed.
	// at the end, jumps to t_label4 or back to t_label2

	// LBL4: Fourth block is "last correction" aka right correction. It is not always executed.
	// at the end, jumps to t_label5

	// LBL5: Fifth block is "nextline", of which there are 3 types.
	// at the end, jumps to t_label1 or to exit

	// In most cases, the t_labelN jump will jump to the associated action block.
	// But before this section is run, the jumps can be configured by the loop setup in such a way 
	// to skip certain blocks.
	// Also, most blocks belong to a certain action type (like COPY, SKIP, FILL), so the jumps will be
	// configured to jump to blocks of the correct action type.

	// todo: for COPYREVX (reverse-X), the setup is different. jump to different setup for that.

	// for normal, non reverse actions, the last jumps are configured first.
	// The action value was saved in t_save_dpl
	// 11-1-2025  in action code, bit5 must be cleared
	ins6(nop, to_t, ld, acc_t, lit32, nop);
	ins6(nop, to_t,  res, acc_t, t_save_dpl, nop);	 // reset bit 5
	ins6(nop, to_mem, ld, acc_t, t_save_dpl, nop);  // store back	


	// At the beginning of the BLIT instruction, t_label5 was configured.

	// first check if DST (dst_x_l) and length (size_x_l) differ in bit0.

	commentline("--- determine label 4 ---");
	ins6(nop,to_t,ld,acc_t,dst_x_l,nop);
	ins6(nop,to_t,xor,acc_t,size_x_l,nop);
	ins6(nop, to_t, and, acc_t, lit1, nop);	 // select bit 0
	ins6(nop, to_t, sub, acc_t, lit1, nop);	// dec T,gives tc=1 if bit0 was set	
	ins6(tc_to_f, to_a, xor, acc_a, lit0, nop); // nop, tc->f
	ins6(nop, to_a, asl, acc_a, lit32, nop);  // A <- 0x40,
	ins6(nop, to_a, add, acc_a, lit32, nop);  // A <- A + 0x20, giving 0x60 (last correction)	
	ins6(nop,to_a,or,acc_a,t_save_dpl,nop); // A <- A OR action value

	// F=0  no difference             F=1  difference
	if_f_t(in_f(nop, to_a, ld, acc_t, t_label5, nop), in_t(nop, to_a, add, acc_a, lit0, nop)); // 31-1-2025  F0: A <- t_label5 F1: nop

	ins6(nop,to_mem,ld,acc_a,t_label4,nop); // store A at label4.

	commentline("--- determine label 3 ---");
	// might bypass counter high bit. Won't do that now, can be added later.
	ins6(nop, to_t, ld, acc_t, BLIT_COUNTHIGH, nop);	// T <- 'counter high bit' action
	ins6(nop,to_mem,ld,acc_t,t_label3,nop); // store T at label3
	// end high bit bypass

	commentline("--- determine label 2 ---");
	// 30-9-2025 problem in blitter solution ?

	// if length==0, set L2 to L3 value. else, set it to action value
	// 28-9-2025  ins6(nop,to_t,ld,acc_t,t_bytecount,nop); // length lsb
	// 28-9-2025  ins6(nop,to_t,or,acc_t,t_bytecount_msb,nop); // or msb	
	// 28-9-2025  ins6(nop, to_t, sub, acc_t, lit1, nop);	// dec T,gives tc=1 if length non-zero
	ins6(tc_to_f,to_a,ld,acc_t,dst_x_l,nop); // A <- dest lsb (for next section), tc->F
	// F=0  length zero, T <- L3 value               F=1  non-zero, T <- action value
	// 28-9-2025. Is this the problem with Sokokban ? Yes, this solves it ! (but need fix in desktop.asm for mouse problem)
	//if_f_t(in_f(nop, to_t, ld, acc_t, t_label3, nop), in_t(nop, to_t, ld, acc_t, t_save_dpl, nop)); //
	//
	ins6(nop, to_t, ld, acc_t, t_save_dpl, nop); // 28-9-2025 new. Always T <- action value

	ins6(nop,to_mem,ld,acc_t,t_label2,nop); // store T at label2
	
	// 30-9-2025 old version
	/*
	// if length==0, set L2 to L3 value. else, set it to action value
	ins6(nop,to_t,ld,acc_t,t_bytecount,nop); // length lsb
	ins6(nop,to_t,or,acc_t,t_bytecount_msb,nop); // or msb	
	ins6(nop, to_t, sub, acc_t, lit1, nop);	// dec T,gives tc=1 if length non-zero
	ins6(tc_to_f,to_a,ld,acc_t,dst_x_l,nop); // A <- dest lsb (for next section), tc->F
	// F=0  length zero, T <- L3 value               F=1  non-zero, T <- action value
	if_f_t(in_f(nop, to_t, ld, acc_t, t_label3, nop), in_t(nop, to_t, ld, acc_t, t_save_dpl, nop)); //

	ins6(nop,to_mem,ld,acc_t,t_label2,nop); // store T at label2
	*/

	commentline("--- determine label 1 ---");
	// if destination odd, L1 <- action + first_correction, else L1 <- action + loop_prepare
	ins6(nop, to_a, and, acc_a, lit1, nop); // select only bit0
	ins6(nop, to_a, sub, acc_a, lit1, nop);	// dec A,gives tc=1 if destination odd

	ins6(tc_to_f, to_a, ld, acc_t, t_save_dpl, nop); // A <- action, f <- tc
	ins6(nop, to_a, add, acc_a, lit32, nop); // add 0x20
	// F=0  dst even. loop_prepare, add 0x20        F=1  dst odd. first-correction, add 0x40
	if_f_t(in_f(nop, to_a, add, acc_a, lit0, nop), in_t(nop, to_a, add, acc_a, lit32, nop)); //
	ins6(nop,to_mem,ld,acc_a,t_label1,nop); // store A at label1

	commentline("--- end blitter loop setup ---");

	// save program counter
	ins6(nop,to_t,ld,acc_t,pcl,nop);  // pcl
	ins6(nop,to_mem,ld,acc_t,t_temp_pcl,nop); // pcl
	ins6(nop,to_pch,ld,acc_t,t_pc_lsb,nop); // write new pcl
	ins6(nop,to_t,ld,acc_t,pcl,nop);  // pch
	ins6(nop,to_mem,ld,acc_t,t_temp_pch,nop); // pch

	make_literal(to_t, ISA_BLIT);
	ins6(nop,to_mem,ld,acc_t,reg_isa,nop);	// set ISA to BLITTER, for correct return after interrupt

	// set line counter  3-1-2025
	ins6(nop,to_t,ld,acc_t,size_y_l,nop);  // size_y_l
	ins6(tc_to_f, to_mem, ld, acc_t, t_linecount, nop); // actually, high byte should also be temp. counter

	// setup PCH/PCL, DPH/DPL.  Same is done at the end of NewLine
	// ins6(nop,to_pch,ld,acc_t,t_pc_lsb,nop); // pc lsb  // done above
	ins6(nop,to_pch,ld,acc_t,t_pc_msb,nop); // pc msb
	ins6(nop, to_dpl, ld, acc_t, t_dp_lsb, nop);	// dpl
	ins6(nop, to_dph, ld, acc_t, t_dp_msb, nop);	// dph	
	ins6(nop, to_t, ld, acc_t, t_dp_msb, nop);	// dph to T	
	//ins6(nop, to_mem, ld, acc_t, t_save_dph, nop);	//  dph to t_save_dph // 11-3 moved to delay

	commentline("--- Goto label 1 ---");

    // 24-3-2025  re-insert 26-3-2025
    ins6(nop, to_mem, ld, acc_t, t_save_dph, nop);        //  dph to t_save_dph.  11-3-2025
    ins6(nop, to_a, ld, acc_t, t_bytecount, nop);        // count (in A) <- bytecount
    ins6(nop, to_t, ld, acc_t, t_bytecount_msb, nop);        // T <- bytecount_msb
    ins6(nop, to_t, ld_ir, acc_t, t_label1, page_blit); // jp to label 1                
    ins6(irq_to_f, to_mem, ld, acc_t, t_count_msb, nop);        // t_count_msb <- T, f <- irq

	print_cycles();


	opcode_page(page_blit, opc_blit_counthigh, "BLIT_COUNTHIGH", nop, nop);
	// handle the high bit of the size-X counter. Note that T is not affected.
	ins6(nop, to_a, dec, acc_a, t_count_msb, nop); // decrement counter
	ins6(tc_to_f, to_mem, ld, acc_a, t_count_msb, nop);	// store counter. tc=0 when it was 0.
	//  F0:  count_msb was 0, to label 4            F1: count_msb was not 0, to label 2
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label4, page_blit), in_t(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit)); // 24-3-2025 add irq_to_f  26-3-2025 again
	
	ins6(nop, to_a, dec, acc_a, lit0, nop); // 25-1-2025  delay, init loop counter to 255

	print_cycles();


	// Interrupt during Blitting

	opcode_page(page_blit, opc_blit_irq, "BLIT_IRQ", nop, nop);

	// The interrupt will preserve ACC and PCH/PCL
	ins6(nop, to_mem, ld, acc_t, t_save_t, nop);	// save T		
	ins6(nop, to_t, ld, acc_t, dpl, nop);	// dpl to T	
	ins6(nop, to_mem, ld, acc_t, t_save_dpl, nop); // save dpl	
	ins6(irq_to_f, to_t, ld_ir, acc_t, reg_kb_state, page_reset);  // jp to interrupt handler of first device (keyboard)
	ins6(nop, to_t, ld, acc_t, lit0, nop);	 // clear T	, seems to be needed. also done in 6502 and z80 interrupt.
	print_cycles();
	

	opcode_page(page_reset, ISA_BLIT, "GBLT", nop, nop);  // used by return from interrupt, back to blitter
	// The interrupt has preserved ACC and PCH/PCL

	// 10-3-2025 interrupt can also come from the new-line. That is the case if t_count_msb has bit7 set.
	ins6(nop, to_t, asl, acc_t, t_count_msb, nop); // bit7 to tc
	ins6(tc_to_f, to_dpl, ld, acc_t, t_save_dpl, nop); // restore dpl  // 10-3  now get tc into f

    //  F=0  bit7 was 0. line was interrupted. restore T        F=1  bit7 was 1. interruption was as NL newline, goto label 5
	if_f_t(in_f(nop, to_t, ld, acc_t, t_save_t,nop), in_t(nop, to_t, ld_ir, acc_t, t_label5, page_blit)); 

	if_f_t(in_f(h_to_f, to_t, ld_ir, acc_t, t_label2, page_blit), in_t(nop, to_t, xor, acc_t, lit0, nop)); // F0: to label 2  F1: delay

	// end 10-3-2025

	ins6(nop, to_dph, ld, acc_t, t_save_dph, nop); // restore dph	(in delay)
	
	print_cycles();	


	opcode_page(page_blit, opc_binc, "BINC", nop, nop);  // 20-3-2025  Blitter Increment DPH, for COPYCNV

	ins6(nop, to_dph, inc, acc_t, t_save_dph, nop);	// inc DPH

	ins6(nop, to_mem, ld, acc_t, t_save_t, nop); // save T  23-3-2025   25-3-2025D
  
	ins6(nop, to_t, inc, acc_t, t_save_dph, nop);	// dph to T	  6-4-2025
    ins6(nop, to_mem, ld, acc_t, t_save_dph, nop);  // save new dph  6-4-2025	

	ins6(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit);  // jp to loop
	
    ins6(nop, to_t, ld, acc_t, t_save_t, nop); // restore T  23-3-2025 // 25-03-2025D

	print_cycles();	


	opcode_page(page_blit, opc_bset2, "BSET2", nop, nop);  // 23-3-2025  Blitter set label 2, for last correction in copycnv

	ins6(nop, to_t, ld, acc_t, t_count_msb, nop);	// get t_label2 from temporary store
	ins6(irq_to_f, to_t, ld_ir, acc_t, t_label5, page_blit);  // jp to label 5
	ins6(nop, to_mem, ld, acc_t, t_label2, nop); // restore label 2
	print_cycles();	


	// Blitter Exit

	opcode_page(page_blit, opc_blit_exit, "BLIT_EXIT", nop, nop);
	// exit. restore PC, restore banking. restore reg_isa.
	ins6(nop, to_t, ld, acc_t, t_temp_reg_isa, nop); // restore reg_isa
	ins6(nop, to_mem, ld, acc_t, reg_isa, nop);	

	// for the TEXT instruction, add x-size to dst-x. Only does sizes less than 256.
	ins6(nop, to_t, ld, acc_t, dst_x_l , nop);	// dest x address
	ins6(nop, to_t, add, acc_t, size_x_l , nop); // add size
	ins6(nop, to_a, inc_tc, acc_t, dst_x_h , nop);	// dest x address high to A, increment if cy
	// to keep it simple, do this for all instructions, not only TEXT
	ins6(nop, to_mem, ld, acc_t, dst_x_l, nop);	
	ins6(nop, to_mem, ld, acc_a, dst_x_h, nop);		

	ins6(nop,to_t,ld,acc_t,lit16, nop); // T <-16   23-2-2025 re-enable interrupts
    ins6(nop,to_t,or,acc_t,reg_irq, nop);    // T <- T or reg_irq (set bit T in reg_irq)
	ins6(nop,to_mem,ld,acc_t,reg_irq, nop);		

	ins6(nop,to_pch,ld,acc_t,t_temp_pcl,nop); // pcl of program code
	ins6(nop,to_pch,ld,acc_t,t_temp_pch,clr_c); // pch of program code	// 6-5-2025 added clr_c

	// And this new stuff also 1 cycle too long...
	//make_literal(to_a, 0x40); // 14-3-2025  T <- 0x40  bit 6 (removed 18-11-2025)
	//ins6(nop, to_t, ld_ir, acc_t, dpl, page_z80_ed); // jump to out (c),A to restore banking
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_out); // 18-11-2025  jump to port_out_sbnk to restore banking	
	//ins6(nop, to_a, or, acc_a, reg_i, nop); // acc <- i OR ACC.  Set bit 6 in acc.
	ins6(nop, to_a, ld, acc_a, reg_i, nop); // 18-11-2025 acc <- i 

	print_cycles();	
}	


function blit_newline(opc,op_name)   // there are 3 types of these: inc_all, dec_all, inc_dst.
									// 25-4-2025  adding type fast_inc
{ 	opcode_page(page_blit, opc, op_name, nop, nop);

	// 25-04-2025A
    // 10-3-2025 new, check interrupt. Also modification in blitter-resume (GBLT)
    ins6(irq_to_f,to_t,ld,acc_t,reg_128,nop)  // if there will be a return from interrupt, then
	
    //  F=0   interrupt                          F=1  no interrupt
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_t, dec, acc_t, t_linecount, nop)); // F0: nop F1: dec line count

	if_f_t(in_f(nop,to_mem,ld,acc_t,t_count_msb,nop), in_t(nop, to_mem, ld, acc_t, t_linecount, nop)); // 25-04-2025A  delay

	// end interrupt check

	// decrement line count

	// 27-4-2025
	ins6(nop, to_a, or_tst, acc_t, size_y_h, nop); // A <- lsb OR msb for zero check 10-3 move it up  27-4-2025 use or_tst
	ins6(nop, to_t, dec_dtc, acc_t, size_y_h, nop);	// dec size_y_h  // 3-1-2025 This also should be a temporary !
	//ins6(nop, to_a, sub, acc_a, lit1, nop);	// dec A,gives tc=0 if linecount is zero
	ins6(dtc_to_f, to_mem, ld, acc_t, size_y_h, nop);	// store, tc->F  27-4-2025 use dtc

	// 14-3-2025 set jump to bankswitch in DPL, in the exit function there is no space for that any more
    /*
	// if line count was zero, we're done, go to exit
	//  F0:  count_msb was 0, to exit            F1: count_msb was not 0, continue
	if_f_t(in_f(nop, to_t, asl, acc_t, lit40,nop), in_t(nop, to_t, ld, acc_t, t_bytecount_msb, nop)); 
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_EXIT, page_blit), in_t(nop, to_mem, ld, acc_t, t_count_msb, nop)); // 25-4
	if_f_t(in_f(nop, to_dpl, add, acc_t, lit41, nop), in_t(nop, to_t, ld, acc_t, src_l_l, nop)); // 27-4-2025	
	*/
	// 18-11-2025   instruction port_out_sbnk (0x1B) to dpl. that is (0x09 << 1) + 0x09
	// if line count was zero, we're done, go to exit
	//  F0:  count_msb was 0, to exit            F1: count_msb was not 0, continue
	if_f_t(in_f(nop, to_t, asl, acc_t, lit9,nop), in_t(nop, to_t, ld, acc_t, t_bytecount_msb, nop)); 
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_EXIT, page_blit), in_t(nop, to_mem, ld, acc_t, t_count_msb, nop)); // 25-4
	if_f_t(in_f(nop, to_dpl, add, acc_t, lit9, nop), in_t(nop, to_t, ld, acc_t, src_l_l, nop)); // 27-4-2025	


    // end of the intro

	// increment/decrement source (DP) to next line
	if (opc != opc_inc_dst)
	{   // 7-4-2025 new
		if (opc == opc_dec_all)
		{  // decrement source line
		ins6(nop, to_t, ld, acc_t, t_dp_lsb, nop); // T <- dp_lsb 
		ins6(nop, to_t, sub, acc_t, src_l_l, nop); // sub src_l_l, cy to tc	
		ins6(nop, to_mem, ld, acc_t, t_dp_lsb, nop); // store

		ins6(nop, to_t, ld, acc_t, t_dp_msb, nop); // load dp_msb
		ins6(nop, to_t, sub_dtc, acc_t, src_l_h, nop); // sub src_length_msb +cy
		
		// check if address fell below #0600 (that value will be #04c0 if its a start of line)
		// (the DEC is only used for screen-to-screen)
		// 8-4-2025
		ins6(nop, to_a, sub_0, acc_t, lit1, nop); // sub 2, result to A
		ins6(nop, to_a, sub, acc_a, lit4, nop); // sub 4, result to A
		// check if carry. if tc=1, we didnt cross the page.		
		ins6(tc_to_f, to_mem, ld, acc_t, t_dp_msb, nop);

		// if tc=0, we crossed the page. address must be set to #FEC0

		// F=0: store new msb, and set BNK to 0.   F=1: nothing
		if_f_t(in_f(nop, to_mem, ld, acc_a, t_dp_msb, nop), in_t(nop, to_t, xor, acc_t, lit0, nop)); 
		
		// now set bank number
		ins6(nop, to_t, asl, acc_t, lit32, nop); // set bit 6 in T
		/* co 17-11-2025
		ins6(nop, to_t, or, acc_t, reg_128, nop); // T <- T or 128. Now T = 11000000.
		*/
		ins6(nop, to_dpl, or, acc_t, reg_128, nop); // 17-11-2025 to dpl.  T <- T or 128. Now T = 11000000.		
		
		// 17-11-2025 remove next line, ucode1117D
		//ins6(nop, to_dpl, or, acc_t, lit8, nop); // set bit3.  Now T = 11001000. Might be reset by a SUB but will be set again lateron. 1-1-2025.

		// for 1st 64k screen section, do not add 2 to bank number (in T): 
	
		// have to write to bnk and to shadow-register
		if_f_t(in_f(nop, to_bnk, ld, acc_a, dpl, nop), in_t(nop, to_t, or, acc_t, lit0, nop)); // F0:  bnk <- dpl	
		ins6(nop, to_t, ld, acc_t, dpl, nop); //  t <- dpl
		if_f_t(in_f(nop, to_mem, ld, acc_t, reg_bank_dp, nop), in_t(nop, to_t, or, acc_t, lit0, nop));  // F0: reg_bank_dp <- t
	
		ins6(nop, to_t, ld, acc_t, t_dp_msb, nop);  // 27-05-2025 moved to here	
		ins6(nop, to_mem, ld, acc_t, t_save_dph, nop); // 27-05-2025 moved to here	
		}
		else
		{  // increment source line
		// 7-4-2025 end new
		//ins6(nop, to_t, ld, acc_t, src_l_l, nop); // T <- src_l_l  27-4-2025 moved to intro
		ins6(nop, to_t, add, acc_t, t_dp_lsb, nop); // add dp_lsb, cy to tc	
		ins6(nop, to_mem, ld, acc_t, t_dp_lsb, nop); // store

		ins6(nop, to_t, ld, acc_t, t_dp_msb, nop); // load dp_msb
		ins6(nop, to_t, add_dtc, acc_t, src_l_h, nop); // add src_length_msb +cy
		ins6(tc_to_f, to_mem, ld, acc_t, t_dp_msb, nop); // store dp_msb, cy to F	

		// check for next source page
		// 7-4-2025A  new, select next screen bank. This whole section should be a new microcode instruction
		//                                          So it doesnt take cycles in most cases.
		// find out if bank changed, if tc=1, a next source page must be selected

		if (opc != opc_fast_inc) // new 25-4-2025. In fast_inc, do not change bank number for dph/dpl (source)
			{
			// when selecting next screen bank, skip the first 0x600 bytes
			if_f_t(in_f(nop, to_t, xor, acc_t, lit0, nop), in_t(nop, to_t, add_1, acc_t, lit1, nop)); // F0: nop F1: add 2
			if_f_t(in_f(nop, to_t, xor, acc_t, lit0, nop), in_t(nop, to_t, add, acc_t, lit4, nop)); // F0: nop F1: add 4
			if_f_t(in_f(nop, to_t, xor, acc_t, lit0, nop), in_t(nop, to_mem, ld, acc_t, t_dp_msb, nop)); // F1: store again

			// now set bank number
			ins6(nop, to_t, asl, acc_t, lit32, nop); // set bit 6 in T
			ins6(nop, to_t, or, acc_t, reg_128, nop); // T <- T or 128. Now T = 11000000.
			// 17-11-2025 remove next line  ucode1117E
			//ins6(nop, to_t, or, acc_t, lit8, nop); // set bit3.  Now T = 11001000. Might be reset by a SUB but will be set again lateron. 1-1-2025.

			// for 2nd 64k screen section, add 2 to bank number (in T): 
			if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_dpl, add_1, acc_t, lit1, nop)); // F1: add 2		

			// have to write to bnk and to shadow-register
			if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_bnk, ld, acc_a, dpl, nop)); // F1:  bnk <- dpl	
			if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_t, ld, acc_t, dpl, nop)); // F1:  t <- dpl
			if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop), in_t(nop, to_mem, ld, acc_t, reg_bank_dp, nop));  // F1: reg_bank_dp <- t
			// 7-4-2025A new end.

			ins6(nop, to_t, ld, acc_t, t_dp_msb, nop); // 27-05-2025 moved to here	
			}

		ins6(nop, to_mem, ld, acc_t, t_save_dph, nop); // 27-05-2025 moved to here			
		
		}

		// 25-4-2025 four lines now here.
		ins6(nop, to_dpl, ld, acc_t, t_dp_lsb, nop);	// dpl
		ins6(nop, to_dph, ld, acc_t, t_dp_msb, nop);	// dph	
	}

	/* 25-4-2025 moved up
	// todo: the section that fills dph/dpl can be moved, to not execute for FILL or XFILL actions.
	ins6(nop, to_dpl, ld, acc_t, t_dp_lsb, nop);	// dpl
	ins6(nop, to_dph, ld, acc_t, t_dp_msb, nop);	// dph	
	ins6(nop, to_t, ld, acc_t, t_dp_msb, nop);	// dph to T	
	ins6(nop, to_mem, ld, acc_t, t_save_dph, nop);	//  dph to t_save_dph
	*/

	// new 7-4-2025
	if (opc == opc_dec_all)
	  {
		// decrement destination (PC) to prev line
		// the decrement value for DST will be the same as for the SRC (only used to copy screen-to-screen)
		// Note that the Y coordinate for DST and SRC must be the BOTTOM line (instead of the upper line)
		ins6(nop, to_t, ld, acc_t, t_pc_lsb, nop); // T <- pc_lsb
		ins6(nop, to_t, sub, acc_t, src_l_l, nop); // sub src_l_l, cy to tc	
		ins6(nop, to_mem, ld, acc_t, t_pc_lsb, nop); // store

		ins6(nop, to_t, ld, acc_t, t_pc_msb, nop); // load pc_msb
		ins6(nop, to_t, sub_dtc, acc_t, src_l_h, nop); // sub src_length_msb +cy
		// check for prev dst page. check if address fell below #0600 (that value will be #04c0 if its a start of line)
		// 8-4-2025
		ins6(nop, to_a, sub_0, acc_t, lit1, nop); // sub 2 result in A
		ins6(nop, to_a, sub, acc_a, lit4, nop); // sub 4 result in A
		// check if carry. if tc=1, we didnt cross the page.
		ins6(tc_to_f, to_mem, ld, acc_t, t_pc_msb, nop); // store pc_msb, f <- tc

		// if tc=0, we crossed the page. address must be set to #FEC0
		// F=0: store new msb, and clear pc17 bit.   F=1: nop's
		if_f_t(in_f(nop, l_to_sw_pc17, ld, acc_t, lit0, nop), in_t(nop, to_t, xor, acc_t, lit0, nop));
		if_f_t(in_f(nop, to_mem, ld, acc_a, t_pc_msb, nop), in_t(nop, to_t, xor, acc_t, lit0, nop)); 

	  }
	else
		{
		// 7-4-2025 end
		// increment destination (PC) to next line
		ins6(nop, to_t, asl, acc_t, lit32, nop); // T <- 64
		ins6(nop, to_t, add, acc_t, t_pc_lsb, nop); // add pcl, cy to tc	
		ins6(nop, to_mem, ld, acc_t, t_pc_lsb, nop); // store

		ins6(nop, to_t, ld, acc_t, t_pc_msb, nop); // load pc_msb
		ins6(nop, to_t, add_dtc, acc_t, lit1, nop); // add 1 plus cy
		ins6(tc_to_f, to_mem, ld, acc_t, t_pc_msb, nop); // store pc_msb, cy to F

		// 25-04-2025A  when no next bank has to be selected, do the last 4 instructions to go to label1

		// if F=1, need to select next screen bank
		if_f_t(in_f(nop, to_a, ld, acc_t, t_bytecount, nop), in_t(nop, h_to_sw_pc17, ld, acc_t, lit0, nop)); // f0: nop F1: pc17 <- 1
		// when selecting next screen bank, skip the first 0x600 bytes
		if_f_t(in_f(nop,to_pch,ld,acc_t,t_pc_lsb,nop), in_t(nop, to_t, add_1, acc_t, lit1, nop)); // F0: nop F1: add 2
		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label1, page_blit), in_t(nop, to_t, add, acc_t, lit4, nop)); // F0: nop F1: add 4
		
		if_f_t(in_f(irq_to_f,to_pch,ld,acc_t,t_pc_msb,nop), in_t(nop, to_mem, ld, acc_t, t_pc_msb, nop)); // 25-04-2025A
		}

	ins6(nop, to_a, ld, acc_t, t_bytecount, nop);        // count (in A) <- bytecount

	// setup PCH/PCL, DPH/DPL.  Same is done at the end of loop setup (in destination calculation)
	ins6(nop,to_pch,ld,acc_t,t_pc_lsb,nop); // pc lsb

	ins6(nop, to_t, ld_ir, acc_t, t_label1, page_blit); // jump back to label 1
	
	ins6(irq_to_f,to_pch,ld,acc_t,t_pc_msb,nop); // 26-3-2025 moved from above // 25-4-2025 added irq_to_f
	print_cycles();	
}


const act_unalign = 0x10;
const act_loop = 0x00;
const act_prepare_loop = 0x20;
const act_first_corr = 0x40;
const act_last_corr = 0x60;

// 1-5-2025 color conversion for Symbos 4-color sprites
//  00 -> 0110 yellow
//  01 -> 0000 black
//  10 -> 0100 red (orange)
//  11 -> 1100 dark red
// The left-most bit is the first bit. Next to it is the second bit.
// First bit selects:   0 -> ld 0000,  1 -> ld 0010    (ld 0010 done with inc(1), for shifted value ld 0x20 )
// Second bit selects:  0 -> xor 0110, 1 -> NOP        (0110 will be in fill1)
// Both bits set:                      1 -> xor 1110   (1110 will be in fill2)
// New Method:
// First bit A selects:   0 -> ld 0100,  1 -> ld 0110 
// Second bit B selects:  0 -> xor 0010, 1 -> SHL       (xor gives 0110 yellow, or 0100 red. SHL gives 1000 black, or 1100 dark red)
// call the values bitA0, bitA1, bitB0.  
// But the SHL is a problem for the 2nd nibble, that should not be shifted !
// Better is, convert to 16-color sprite. Just shifting bits !


function blit_action(opc,op_name)   // main actions of the blitter. 
{   // the name will be constructed from the opcode
	var act = opc & 0x60;
	if (act == 0x00) { mode = "loop"; mnem=" "; }
	if (act == 0x20) { mode = "Prepare-loop"; mnem = "P"; }
	if (act == 0x40) { mode = "First-correction"; mnem= "F"; };
	if (act == 0x60) { mode = "Last-correction"; mnem = "L"; }
	if (opc & 0x10) { alg = "Unaligned"; ma="U" } else { alg=""; ma="_" }

	instr_name = "B"+ma+op_name+mnem;

	var skipflag = 0;

	opcode_page(page_blit, opc | 0x80, instr_name, nop, nop);  // instructions are at 0x80 - 0xFF on page_blit
	var str;

	if (op_name=='N') str="CopyCNV";	// 20-3-2025
	if (op_name=='R') str="Reverse-x-copy";	
	if (op_name=='2') str="copy24";
	if (op_name=='S') { str="Skip"; skipflag = 1; }		// 20-3-2025
	if (op_name=='V') str="saVe";
	if (op_name=='T') str="Text";	
	if (op_name=='F') str="Fill";
	if (op_name=='X') str="Xfill";	
	if (op_name=='M') str="Skip24";	
	if (op_name=='C') str="Copy";

	commentline("--- "+alg+" "+str+" "+mode+" ---"); // readable instruction name

    // 20-3-2025  use N instead of C
    if (op_name=='R') 
	   { op_name='N'; commentline("--- Instead of reverse-X, normal copy is used. Has to be changed."); }
    if (op_name=='S') 
	   { op_name='N'; commentline("--- Normal copy is used. But looks at skipflag."); }
    if (op_name=='M') 
	   { op_name='2'; commentline("--- Instead of SKIP24, normal COPY24 is used. Has to be changed."); }


	// instruction starts here

	if ( (act == act_prepare_loop) || (act == act_first_corr) ) // prepare. might be the same for all actions.
		{ 	}
	// -------  action: FILL  -------

	if ( (act == act_first_corr) && (op_name =="F") ||  // first correction fill	
         (act == act_prepare_loop) && (op_name =="F") && (ma=="U") )
	{	
		// 29-1-2025 do correction
        ins6(nop, to_t, ld, acc_t, reg_0F, nop);   // select lower 4 bits. lower4 bits are reset in next cycle.		
		ins6(nop, to_t, res, acc_t, pc_lin_ind, bank0);  // get 2 pixels from (pc). change only lower 4 bits.
		ins6(nop, to_t, or, acc_t, fill_1, nop);  // put fill color, only lower 4 bits
		
		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);		// store and inc pc
		ins6(nop, to_t, ld, acc_t, fill_1, nop);  // set fill color
		ins6(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2   25-3-2025D add irq_to_f
		ins6(nop, to_t, or, acc_t, t_fill_2_sh4, nop);   // fill_2 color to high nibble, in delay  25-1-2025		
	}
	else
	if ( (act == act_prepare_loop) && (op_name =="F") )  // prepare fill
	{	
		ins6(nop, to_t, ld, acc_t, fill_1, nop);  // set fill color 
		ins6(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2   25-3-2025D add irq_to_f
		ins6(nop, to_t, or, acc_t, t_fill_2_sh4, nop);   // fill_2 color to high nibble, in delay  25-1-2025
	}
	
	if ( (act == act_loop) && (op_name =="F") )  // fill loop. partially unrolled (per 3 bytes)
	{	
		// 27-12-2024
		//   For FILL:
		//   F0: jp int      F1: dec A
		//       delay           (pc++)<-T, F<-tc  <-- slightly changed !
		//       jp label3       jp label2, F<-IRQ
		//       delay           delay

	
		// 12-9-2025 :
		// F=0  interrupt, F <- 1                F=1  no interrupt, (pc++) <- T  Uses linear PC mode !
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  jp int, F1: dec A
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f,to_t, xor, acc_t, lit0,nop ) );   //   nop,  F1: 12-9-2025 nop, F<-tc
		// partially unrolling the loop 28-12-2024
		// F=0  count reached zero. to label 3.  F=1 fill next byte		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  jp int, F1: dec A
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_mem, ld, acc_t, pc_lin_pp, bank0) );   //   nop,  F1: (pc++)<-T, F<-tc
		// partially unrolling the loop  28-12-2024
		// F=0  count reached zero. to label 3.  F=1 fill next byte		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  jp int, F1: dec A
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_mem, ld, acc_t, pc_lin_pp, bank0) );   //   nop,  F1: (pc++)<-T, F<-tc

		// F=0  count reached zero. to label 3.        F=1  normal, to loop (label2)
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(nop, to_t, ld_ir, acc_t, t_label2, page_blit)); // exit(label3), F1: label2
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(irq_to_f, to_mem, ld, acc_t, pc_lin_pp, bank0 ) );   // nop , F1: (pc++)<-T 12-9-2025
		//ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);  // 12-9-2025

		// 8 cycles per 3 filled bytes
	}
	if ( (act == act_last_corr) && (op_name =="F") )  // fill last correction.
	{	// new 30-1-2025		
		ins6(nop, to_t, ld, acc_t, pc_lin_ind, bank0);  // get 2 pixels from (pc). change only upper 4 bits.
		ins6(nop, to_t, and, acc_t, reg_0F, nop);   // keep lower 4 bits
		ins6(nop, to_t, or, acc_t, t_fill_2_sh4, nop);  // put fill color, in upper 4 bits		
		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);		// store and inc pc		
		
		ins6(nop, to_t, ld_ir, acc_t, t_label5, page_blit); // jump to label 5
		ins6(nop, to_t, xor, acc_t, lit0, nop);  // nop, delay
	}

	// -------  action: FXOR  -------   29-12-2024

    // 31-1-2025 correction for FXOR
	if ( (act == act_first_corr) && (op_name =="X") ||  // first correction xfill	
         (act == act_prepare_loop) && (op_name =="X") && (ma=="U") )
	{	    
		// 16-3-2025 use a single XOR value, in fill_1

		ins6(nop, to_t, ld, acc_t, fill_1, nop);  // set fill color		
		ins6(nop, to_t, or, acc_t, t_fill_2_sh4, nop); 
		ins6(nop, to_mem, ld, acc_t, fill_1, nop);  // store in Fill1
		ins6(nop, to_t, ld, acc_t, lit0, nop); // clr T
		ins6(nop, to_mem, ld, acc_t, t_fill_2_sh4, nop); // set fill_2_sh4 to zero		
		// Now swap nibbles in Fill_1
		ins6(nop, to_dpl, ld, acc_t, fill_1, nop);  // get fill color	
		ins6(nop, to_dph, inc, acc_t, lit1, nop); // MSB of nibble swap table (0200 -02FF) in bank2
		ins6(nop, to_t, ld, acc_a, ext, bank2);  // T <- swaptable(dph|dpl), bank2
		ins6(nop, to_mem, ld, acc_t, fill_1, nop);  // store in Fill1


		ins6(nop, to_t, ld, acc_t, fill_1, nop);  // get fill color, only lower 4 bits
		ins6(nop, to_t, and, acc_t, reg_0F, nop);  // clear upper nibble		
		ins6(nop, to_t, xor, acc_t, pc_lin_ind, bank0);  // OR with 2 pixels from (pc).
		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);		// store and inc pc

		ins6(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit); // 16-3 jump to label 2	   25-3-2025D add irq_to_f
		ins6(nop, to_t, ld, acc_t, fill_1, nop);  // 16-3 set fill colors
	}
	else
	if ( (act == act_prepare_loop) && (op_name =="X") )  // prepare xfill
	{	// 16-3-2025 use a single XOR value, in fill_1
		ins6(nop, to_t, ld, acc_t, fill_1, nop);  // set fill color		
		ins6(nop, to_t, or, acc_t, t_fill_2_sh4, nop); 
		ins6(nop, to_mem, ld, acc_t, fill_1, nop);  // store in Fill1
		ins6(nop, to_t, ld, acc_t, lit0, nop); // clr T
		ins6(nop, to_mem, ld, acc_t, t_fill_2_sh4, nop); // set fill_2_sh4 to zero		
		// Now swap nibbles in Fill_1
		ins6(nop, to_dpl, ld, acc_t, fill_1, nop);  // get fill color	
		ins6(nop, to_dph, inc, acc_t, lit1, nop); // MSB of nibble swap table (0200 -02FF) in bank2
		ins6(nop, to_t, ld, acc_a, ext, bank2);  // T <- swaptable(dph|dpl), bank2
		ins6(nop, to_mem, ld, acc_t, fill_1, nop);  // store in Fill1		

		ins6(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit); // 16-3 jump to label 2	   25-3-2025D add irq_to_f
		ins6(nop, to_t, ld, acc_t, fill_1, nop);  // 16-3 set fill colors

	}

	if ( (act == act_loop) && (op_name =="X") )  // fill loop. can even be unrolled, not done yet.
	{	// 29-12-2024
		//   For XFILL: (have fill in T)
		//   F0: jp int      F1: dec A
		//       delay           T <- T xor (pc), F <- tc
		//                       (pc++)<-T
		//       jp label3       jp label2, F<-IRQ
		//       T <- fill       T <- fill
	
		// 22-3-2025
		// The above version did one byte too much
		//   F0: jp int      F1: dec A
		//       delay           T <- T xor (pc), F <- tc
		//       jp label3		 (pc++)<-T       
		//       T <- fill       jp label2, F<-IRQ
		//                       T <- fill

 		// F=0  interrupt, F <- 1                F=1  no interrupt, (pc++) <- T  Uses linear PC mode !
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  jp int, F1: dec A
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_t, xor, acc_t, pc_lin_ind, bank0) );   //   nop,  F1: T <-T xor (PC), F<-tc

	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(nop, to_mem, ld, acc_t, pc_lin_pp, bank0)); // exit(label3), F1: (pc++)<-T

	    if_f_t(in_f(nop, to_t, ld, acc_t, fill_1, nop), in_t(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit)); // T <- fill1, F1: label2		

		ins6(nop, to_t, ld, acc_t, fill_1, nop);

		// 6 cycles per xor'ed byte,  16-3-2025 5 cycles per byte
	}
	if ( (act == act_last_corr) && (op_name =="X") )  // fill last correction. 
	{	// new 31-1-2025		
		// 16-3-2025
		ins6(nop, to_t, ld, acc_t, reg_0F, nop);  // will clear lower nible
		ins6(nop, to_t, res, acc_t, fill_1, nop);  // get XOR fill color, clear lower nibble
		ins6(nop, to_t, xor, acc_t, pc_lin_ind, bank0);  // XOR with 2 pixels from (pc). change only upper 4 bits.
		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);		// store and inc pc		
				
		ins6(nop, to_t, ld_ir, acc_t, t_label5, page_blit); // jump to label 5
		ins6(nop, to_t, xor, acc_t, lit0, nop);  // nop, delay
	}


	// -------  action: COPY  -------  28-12-2024

	// 9-4-2025 new

	if (ma != "U")
	{                //   ALIGNED version

	if ( (act == act_prepare_loop) && (op_name =="C") )  // prepare copy
	{	
		ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2
		ins6(irq_to_f, to_t, ld, acc_t, ext, nop ); // T <- (DP)  //first byte  (in delay)
	}
	if ( (act == act_first_corr) && (op_name =="C") )  // first corr copy
	{	
		// what should it do:
		//  T <- (dp)
		//  T <- T and 0F  // clear upper
		//  reg_vga_acc <- T  // save result
		//  T <- (pc_lin_ind)
		//  T <- T res 0F  // clear lower
		//  T <- T or reg_vga_acc  // result
		//  ... store at (PC_LIN++) ??
		// inc DP
		// T <- DP  // irq_to_f, go to loop

		// 22-3-2025A  first correction. High nibble always transparent.
		ins6(irq_to_f, to_t, ld, acc_t, ext, nop ); // get source data
		ins6(nop,to_t,and,acc_t,reg_0F,nop); // clear high nibble, will be transparent
		ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop); // save it. There will be no vga interrupt before we use this, so it's ok.

		ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get screen contents
		ins6(nop,to_t,res2,acc_t,reg_0F,nop); // clear low nibble, becomes color 0
			                                    
		ins6(nop,to_t,or,acc_t,reg_vga_acc,nop);  // combination of both nibbles

		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, nop ); // store at (pc++)
		ins6(nop, to_dpl, inc, acc_t, dpl, nop);    // and increment source pointer
		
		ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit);  // jp to the copy function
		ins6(irq_to_f, to_t, ld, acc_t, ext, nop ); // T <- (DP)  //first byte  (in delay)
	}	
	if ( (act == act_loop) && (op_name =="C") )  // copy loop. 
	{			
		// this copied from "C" copy function, 8-4-2025
		// 27-12-2024 (for copy)
		//   F0: jp int      F1: dec A   // when the loop starts, the current (DP) is in T.
		//       delay           F<-tc
		//
		//       jp label3       dpl++
		//       delay           (pc++)<-T, F<-tc 
		//
		//       jp label2       dph <- inc(t_save_dph)
		//       T<-(DP),F<-irq  T <- inc(t_save_dph) 
		//                       t_save_dph <- T
		//                       jp label2
		//                       T<-(DP),F<-irq
		// F=0  interrupt, F <- 1                F=1  no interrupt, (pc++) <- T  Uses linear PC mode !
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  jp int, F1: dec A
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_t, xor, acc_t, lit0, nop) );   //   nop,  F1: F<-tc

		// F=0  count reached zero. to label 3.  F=1  dpl++		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(nop, to_dpl, inc, acc_a, dpl, nop)); //  jp exit, F1: inc dpl
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_mem, ld, acc_t, pc_lin_pp, nop) );   //   nop,  F1: (pc++)<-T, F<-tc

		// F=0  normal, to loop (label2).  F=1  when dpl++ had carry, increment dph		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label2,page_blit ), in_t(nop, to_dph, inc, acc_t, t_save_dph, nop)); //  jp loop, F1: dph <- inc (save_dph)
	    if_f_t(in_f(irq_to_f, to_t, ld, acc_t, ext, nop ), in_t(nop, to_t, inc, acc_t, t_save_dph, nop)   );   //   nop,  F1: T <- inc(t_save_dph) 
		ins6(nop, to_mem, ld, acc_t, t_save_dph, nop );   // t_save_dph <- T
		ins6(nop, to_t, ld_ir, acc_t, t_label2,page_blit );
		ins6(irq_to_f, to_t, ld, acc_t, ext, nop );		
	}

	if ( (act == act_last_corr) && (op_name =="C") )  // copy last correction. 
	{	// should, at the end, go to label5/page_blit

		 // what should it do:
		//  T <- (dp)
		//  T <- T res2 0F  // clear lower
		//  reg_vga_acc <- T  // save result
		//  T <- (pc_lin_ind)
		//  T <- T and 0F  // clear upper
		//  T <- T or reg_vga_acc  // result
		//  ... store at (PC_LIN++) ??
		// 
		//   // irq_to_f, go to label5

		// 9-4-2025  last correction.
		ins6(irq_to_f, to_t, ld, acc_t, ext, nop ); // get source data
		ins6(nop,to_t,res2,acc_t,reg_0F,nop); // clear low nibble
		ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop); // save it. There will be no vga interrupt before we use this, so it's ok.

		ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get screen contents
		ins6(nop,to_t,and,acc_t,reg_0F,nop); // clear high nibble
			                                    
		ins6(nop,to_t,or,acc_t,reg_vga_acc,nop);  // combination of both nibbles
		
		ins6(nop, to_t, ld_ir, acc_t, t_label5, page_blit);  // jp to end of line
		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, nop ); // store at (pc++)
	}

	} // if (ma != "U")

	if (ma == "U")
    {

    // 9-4-2025  unaligned copy,  adapted from copycnv

	if ( (act == act_prepare_loop) && (op_name =="C") )  // prepare copy  unaligned
	{	  // 24-3-2025
		  // non transparent
		  { 
			ins6(nop, to_t, ld, acc_t, ext, nop ); // T <- (DP)
			ins6(nop, to_dpl,and,acc_t,reg_0F, nop); // clear high nibble, result to dpl
			
			// but color must be in high nibble !
			ins6(nop, to_dph,inc,acc_t,lit1, nop);  // address of nibble swap table, msb=2, bank2
			ins6(nop, to_t, ld, acc_t, ext, bank2); // get color to high nibble

			ins6(nop, to_dpl,inc,acc_t,t_dp_lsb, nop);  // restore dpl (and inc dpl)
			ins6(tc_to_f, to_dph,ld,acc_t,t_save_dph, nop); // restore dph F <- tc	

		  }
  
		//  F0: inc DPL had no CY. go to loop.    F1: inc DPL had CY. jump to BINC that will increment DPH
		if_f_t(in_f(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit), in_t(irq_to_f, to_t, ld_ir, acc_t, lit41, page_blit)); 		   
	    ins6(nop, to_t, res2, acc_t, reg_0F, nop); // T <- T AND F0

	}
	if ( (act == act_first_corr) && (op_name =="C") )  // first corr copy  unaligned
	{	// 24-3-2025
 		ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get screen contents
		ins6(nop,to_t,res2,acc_t,reg_0F,upd_c); // clear low nibble, clear CY
		ins6(nop, to_mem, ld, acc_t, t_save_t, nop);  // t_save_t <- T			
		
	   	ins6(h_to_f, to_t, ld_ir, acc_t, ext, page_cp_u);  // jp to the copy function, F <- 1

		ins6(nop, to_dpl, inc, acc_t, dpl, upd_c); // inc dpl, upd_c

	}	
	if ( (act == act_loop) && (op_name =="C") )  // copy loop. unaligned.  DONE 23-3-2025
	{	
		//  (for copycnv-unaligned)
		//   F0: jp int      F1: dec A
		//       delay           t_save_t <-T, F <- tc 
		//
		//   F0: jp label3   F1: IR<-(DPH/DPL), page_copycnv_un   (jp to unaligned color conversion)  <-- change to page_cp_u
		//       delay           inc DPL,  F <-0 (transp) or F <- 1 (non transp) 

		// F=0  interrupt, F <- 1                F=1          Uses linear PC mode !
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  jp int, F1: dec A

	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_mem, ld, acc_t, t_save_t, nop) ); //

		// F=0  count reached zero. to label 3.  F=1  dpl++		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(nop, to_t, xor, acc_t, lit0,nop)); //  F0: jp exit, F1: nop

		//if (skipflag==1) // transparent
	 
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(h_to_f, to_t, ld_ir, acc_t, ext, page_cp_u)); //  F0: delay F1: jp to colorconv. F=1

		ins6(nop, to_dpl, inc, acc_t, dpl, upd_c); // inc dpl, upd_c
	}
	if ( (act == act_last_corr) && (op_name =="C") )  // copy last correction. 
	{	// 24-3-2025  last correction. Same for transp and non-transp.
	   
		ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get screen contents
		ins6(nop,to_t,and,acc_t,reg_0F,nop); // clear high nibble
		ins6(nop,to_t,or,acc_t,t_save_t,nop);  // or with the last nibble of prev round

		ins6(nop, to_t, ld_ir, acc_t, t_label5, page_blit);  // temp, go to the end
		ins6(nop, to_mem,ld,acc_t,pc_lin_pp, nop); // store the result, only upper nibble changed.
	}  

	} // if (ma == "U")



	// -------  action: COPYCNV  "N"  -------  19-3-2025   copy and convert color. Can also optionally do transparency (SKIP).

	if (ma != "U")
	{                //   ALIGNED version

	if ( (act == act_prepare_loop) && (op_name =="N") )  // prepare copy
	{	
		ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2
		ins6(irq_to_f, to_t, ld, acc_t, ext, nop ); // T <- (DP)  //first byte  (in delay)
	}
	if ( (act == act_first_corr) && (op_name =="N") )  // first corr copy
	{		
		// 22-3-2025A  first correction. High nibble always transparent.
		ins6(irq_to_f, to_t, ld, acc_t, ext, nop ); // get source data
		ins6(nop,to_t,and,acc_t,reg_0F,nop); // clear high nibble, will be transparent
		ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop); // save it. There will be no vga interrupt before we use this, so it's ok.

		// Low nibble transparent or color 0
		// put that in T:  <transp> <transp or 0>
		if (skipflag==1) 
		  { ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // transparent on both nibbles
		  }
		else
		  { ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get screen contents
			ins6(nop,to_t,res2,acc_t,reg_0F,nop); // clear low nibble, becomes color 0
			                                      // TODO put the Isetta color equiv of Symbos color 0 here.
			ins6(nop,to_t,or,acc_t,fill_1,nop);  // 26-3-2025
		  }		

		ins6(nop, to_t, ld_ir, acc_t, reg_vga_acc, page_copycnv);  // jp to the copy function
		ins6(nop, to_dpl, inc, acc_t, dpl, nop);    // and increment source pointer

	}	
	if ( (act == act_loop) && (op_name =="N") )  // copy loop. 
	{	
		//  (for copycnv)
		//   F0: jp int      F1: dec A
		//       delay           T <- (PC), F <- tc (or T is zero, for non-transp.)
		//   F0: jp label3   F1: IR<-(DPH/DPL), page_copycnv
		//       delay           inc DPL 

		// F=0  interrupt, F <- 1                F=1          Uses linear PC mode !
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  jp int, F1: dec A

		if (skipflag==1) // 20-3-2025
	      if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_t, ld, acc_t, pc_lin_ind, bank0) );   //  F0: nop  F1: T <- (PC), F <- tc 
		else  // 20-3-2025
            
             // 24-3-2025  re-insert 26-3-2025
             {  if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_t, ld, acc_t, fill_1, nop) ); // use the color alternative for skip code, low
                if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(nop, to_t, or, acc_t, t_fill_1_sh4, nop) ); // high nibble
             }		  

		// F=0  count reached zero. to label 3.  F=1  dpl++		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(nop, to_t, ld_ir, acc_t, ext, page_copycnv)); //  F0: jp exit, F1: jp to colorconv.
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(nop, to_dpl, inc, acc_t, dpl, nop) );   //   F0: nop,  F1: inc dpl

		// max 4 + 7 cycles per transferred byte (if non transparent)
	}
	if ( (act == act_last_corr) && (op_name =="N") )  // copy last correction. no action here yet
	{	// 23-3-2025  last correction. High nibble always transparent.
		ins6(irq_to_f, to_t, ld, acc_t, ext, nop ); // get source data
		ins6(nop,to_t,res2,acc_t,reg_0F,nop); // clear low nibble, will be transparent
		ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop); // save it. There will be no vga interrupt before we use this, so it's ok.

	    // The function in page_copycnv will convert the color and might apply transparency.
		// But it will normally return to the beginning of the loop, via t_label2. That is not want we want here.

		// so change the jump in t_label2, to a special function that sets label2 back and goes to label5.
		// called: BSET2.  At 0x10.
		ins6(nop, to_t, ld, acc_t, t_label2, nop ); // get label2 value to store it somewhere
		ins6(nop, to_mem, ld, acc_t, t_count_msb , nop );	// store at t_count_msb

		ins6(nop, to_t, ld, acc_t, BLIT_BSET2, nop );  // set new label2 value. copcycnv will jp to this.
		ins6(nop, to_mem, ld, acc_t, t_label2, nop );		

		// Low nibble transparent or color 0
		// put that in T:  <transp> <transp or 0>
		if (skipflag==1) 
		  { ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // transparent on both nibbles
		  }
		else
		  { ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get screen contents
			ins6(nop,to_t,and,acc_t,reg_0F,nop); // clear high nibble, becomes color 0 
			                                     // TODO put the Isetta color equiv of Symbos color 0 here.
			ins6(nop,to_t,or,acc_t,t_fill_1_sh4,nop);  // 26-3-2025												 
		  }	

		ins6(nop, to_t, ld_ir, acc_t, reg_vga_acc, page_copycnv);  // jp to the copy function
		ins6(nop, to_dpl, inc, acc_t, dpl, nop);    // and increment source pointer. (Would not be needed, last pixel on this line)
		
	}


	} // if (ma != "U")

    // ----- UNALIGNED version of "N" COPYCNV ---------  23-3-2025

    else  // (ma == "U")
    {

    // 25-3-2025F  restored unaligned copy

	if ( (act == act_prepare_loop) && (op_name =="N") )  // prepare copy  unaligned
	{	// 24-3-2025
		if (skipflag==1) // transparent
		  { ins6(nop, to_t, ld, acc_t, ext, nop ); // T <- (DP)
			ins6(nop, to_t,and,acc_t,reg_0F, nop); // clear high nibble
			ins6(nop, to_t,sub,acc_t,lit1, nop);  // check for zero
		
			// 26-3-2025
			ins6(tc_to_f, to_t, ld, acc_t, reg_128,nop ); // F <- tc // make address #B0 of nontransparent-prepare unaligned
			ins6(nop, to_t, add, acc_t, lit32,nop );   // #80 + #20 = #A0 
			ins6(nop, to_dpl, add, acc_t, lit16,nop ); // #A0 + #10 = #B0 		26-3-2025B changed to lit16				

			//  F0: nop                                  F1: jump to non-transparent prepare
			if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop), in_t(irq_to_f, to_t, ld_ir, acc_t, dpl, page_blit)); 	
			
			ins6(nop, to_dpl, ld, acc_t, t_dp_lsb, nop); // 25-3-2025G   delay, restore dpl				   

			// transparent
			ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get screen contents
			ins6(nop, to_dpl, inc, acc_t, dpl, nop);
			ins6(tc_to_f, to_t, xor, acc_t, lit0,nop ) // F <- tc			
		  }
		else  // non transparent
		  {
			ins6(nop, to_t, ld, acc_t, ext, nop ); // T <- (DP)
			ins6(nop, to_dpl,and,acc_t,reg_0F, nop); // clear high nibble, result to dpl
			ins6(nop, to_dph,inc,acc_t,lit9, nop);  // value 0x0A to dph, address of color conversion table  TODO change to ROM-based conversion ?
			ins6(nop, to_dpl, ld, acc_t, ext, bank1); // get color 
			// but color must be in high nibble !
			ins6(nop, to_dph,inc,acc_t,lit1, nop);  // address of nibble swap table, msb=2, bank2
			ins6(nop, to_t, ld, acc_t, ext, bank2); // get color to high nibble

			ins6(nop, to_dpl,inc,acc_t,t_dp_lsb, nop);  // restore dpl (and inc dpl)
			ins6(tc_to_f, to_dph,ld,acc_t,t_save_dph, nop); // restore dph F <- tc	

		  }
  
		//  F0: inc DPL had no CY. go to loop.    F1: inc DPL had CY. jump to BINC that will increment DPH
		if_f_t(in_f(irq_to_f, to_t, ld_ir, acc_t, t_label2, page_blit), in_t(irq_to_f, to_t, ld_ir, acc_t, lit41, page_blit)); 		   
	    ins6(nop, to_t, res2, acc_t, reg_0F, nop); // T <- T AND F0

	}
	if ( (act == act_first_corr) && (op_name =="N") )  // first corr copy  unaligned
	{	// 24-3-2025		
 		ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get screen contents
		ins6(nop,to_t,res2,acc_t,reg_0F,upd_c); // clear low nibble, clear CY
		ins6(nop, to_mem, ld, acc_t, t_save_t, nop);  // t_save_t <- T			
		
		if (skipflag==1)
		   { ins6(l_to_f, to_t, ld_ir, acc_t, ext, page_copycnv_un); } // jp to the copy function, F <- 0
		else  
		   { ins6(h_to_f, to_t, ld_ir, acc_t, ext, page_copycnv_un); } // jp to the copy function, F <- 1

		ins6(nop, to_dpl, inc, acc_t, dpl, upd_c); // inc dpl, upd_c
    
	}	
	if ( (act == act_loop) && (op_name =="N") )  // copy loop. unaligned.  DONE 23-3-2025
	{	
		//  (for copycnv-unaligned)
		//   F0: jp int      F1: dec A
		//       delay           t_save_t <-T, F <- tc 
		//
		//   F0: jp label3   F1: IR<-(DPH/DPL), page_copycnv_un   (jp to unaligned color conversion)
		//       delay           inc DPL,  F <-0 (transp) or F <- 1 (non transp) 

		// F=0  interrupt, F <- 1                F=1          Uses linear PC mode !
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  jp int, F1: dec A

	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_mem, ld, acc_t, t_save_t, nop) ); //

		// F=0  count reached zero. to label 3.  F=1  dpl++		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(nop, to_t, xor, acc_t, lit0,nop)); //  F0: jp exit, F1: nop

		if (skipflag==1) // transparent
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(l_to_f, to_t, ld_ir, acc_t, ext, page_copycnv_un)); //  F0: delay F1: jp to colorconv. F=0
		else
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(h_to_f, to_t, ld_ir, acc_t, ext, page_copycnv_un)); //  F0: delay F1: jp to colorconv. F=1

		ins6(nop, to_dpl, inc, acc_t, dpl, upd_c); // inc dpl, upd_c
	}
	if ( (act == act_last_corr) && (op_name =="N") )  // copy last correction. 
	{	// 24-3-2025  last correction. Same for transp and non-transp.
	   
		ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get screen contents
		ins6(nop,to_t,and,acc_t,reg_0F,nop); // clear high nibble
		ins6(nop,to_t,or,acc_t,t_save_t,nop);  // or with the last nibble of prev round

		ins6(nop, to_t, ld_ir, acc_t, t_label5, page_blit);  // temp, go to the end
		ins6(nop, to_mem,ld,acc_t,pc_lin_pp, nop); // store the result, only upper nibble changed.
	}  

	} // if (ma == "U")


	// -------  action: TEXT  -------  31-12-2024

	// 29-1-2025 ma=="U"  means "Unaligned" (the text starts at an odd screen position)

	if ( (act == act_first_corr) && (op_name =="T") && (ma !="U") ) // first correction TEXT, aligned	        
	{			
		ins6(nop,to_t,ld,acc_t,dpl,nop); // T <- dpl
		ins6(nop,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T  save dpl		
		
		ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop );  // dpl <- (DP)  //first byte  (in delay)
        // new section 29-1-2025
        ins6(nop,to_dpl,asl,acc_t,dpl,nop) ;   //  dpl <- asl(dpl)   A single pixel. pixel in low nibble must be replaced
		ins6(tc_to_f, to_t, ld, acc_t, reg_0F, nop); //  f <- tc
		ins6(nop, to_t, res, acc_t, pc_lin_ind, bank0);  // get current (pc), reset bit 0-3
		if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0:  BG low nibble  F1:  FG low nibble		
        ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2	
		ins6(irq_to_f, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the old and new pixels, inc pc, irq_to_f
	}	
	else
	if ( (act == act_prepare_loop) && (op_name =="T") && (ma !="U") )  // prepare text, aligned
	{			
		ins6(nop,to_t,ld,acc_t,dpl,nop); // T <- dpl
		ins6(nop,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T  save dpl
		
		ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2
		ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop ); // dpl <- (DP)  //first byte  (in delay)
	}	


	if ( (act == act_first_corr) && (op_name =="T")&& (ma=="U") )  // first correction TEXT, Unaligned	       
	{			
		ins6(nop,to_t,ld,acc_t,dpl,nop); // T <- dpl
		ins6(nop,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T  save dpl		
		
		ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop );  // dpl <- (DP)  //first byte  (in delay)
        // new section 29-1-2025
        ins6(nop,to_dpl,asl,acc_t,dpl,nop) ;   //  dpl <- asl(dpl)   A single pixel. pixel in low nibble must be replaced
		ins6(tc_to_f, to_t, ld, acc_t, reg_0F, nop); //  f <- tc
		ins6(nop, to_t, res, acc_t, pc_lin_ind, bank0);  // get current (pc), reset bit 0-3
		if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0:  BG low nibble  F1:  FG low nibble		
        ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2	
		ins6(irq_to_f, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the old and new pixels, inc pc, irq_to_f
	}	
	else
	if ( (act == act_prepare_loop) && (op_name =="T") && (ma=="U") )  // prepare text, Unaligned
	{			
		ins6(nop,to_t,ld,acc_t,dpl,nop); // T <- dpl
		ins6(nop,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T  save dpl
		
		ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2
		// 6-10-2025 old:
		//ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop ); // dpl <- (DP)  //first byte  (in delay)

		// 6-10-2025:
		ins6(irq_to_f, to_dpl, asl, acc_t, ext, nop ); // dpl <- (DP)  //first byte  (in delay), skip first bit !
	}	

	if ( (act == act_loop) && (op_name =="T") && (ma == "U"  ))  // copy text. UnAligned. new 30-1-2025. Goes together with the above first_correction
	{	
		// F=0  interrupt, F <- 1                F=1  no interrupt
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  F0: jp int, F1: dec A
		no_f_write_error = 1;
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   // F0:  nop,  F1: dpl <- asl(dpl),  f <- tc
		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   //   F0: jp exit  F1: (pc++)<-T, F<-tc
		no_f_write_error = 0;

		if_f_t(in_f(tc_to_f, to_t, ld, acc_t, t_fill_2_sh4,nop ), in_t(tc_to_f,to_t,ld,acc_t,t_fill_1_sh4,nop) );   //   F0: pix7, BG  F1: pix7, FG
		if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0: pix6, BG  F1: pix6, FG

		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the two pixels
	
		var i=2;  // pixels 5,4 and 3,2 
		while (i != 0)
		{	ins6(nop, to_a, sub, acc_a, lit1, nop); // dec A
			no_f_write_error = 1;
			ins6(tc_to_f,to_dpl,asl,acc_t,dpl,nop); // dpl <- asl(dpl),  f <- tc
			
			if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3, page_blit ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   //   F0: jp exit  F1: (pc++)<-T, F<-tc
			no_f_write_error = 0;

			if_f_t(in_f(tc_to_f, to_t, ld, acc_t, t_fill_2_sh4,nop ), in_t(tc_to_f,to_t,ld,acc_t,t_fill_1_sh4,nop) );   //   F0: pix7, BG  F1: pix7, FG
			if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0: pix6, BG  F1: pix6, FG

			if (i != 1)  ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the two pixels
			i = i-1;
		}
		// pixels 1,0.

		ins6(nop, to_a, sub, acc_a, lit1, nop); // dec A

		// new 6-10-2025
		ins6(tc_to_f, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the two pixels (last one in the above loop)		

		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3, page_blit ), in_t(nop,to_t,inc,acc_t,t_txt_lsb,nop) );   //   F0: jp exit  F1: T <- inc (t_txt_lsb)		
		if_f_t(in_f(nop, to_t, xor, acc_t, lit0, nop ), in_t(nop,to_mem,ld,acc_t,t_txt_lsb,nop) );              //   F0: delay    F1: t_txt_lsb <- T

		ins6(nop,to_dpl,asl,acc_t,dpl,nop); // dpl <- asl(dpl)		
		ins6(tc_to_f, to_dpl, xor, acc_t, lit0, nop ); // dpl < T, F <- tc

		ins6(nop, to_dpl, asl, acc_t, ext, nop ); // dpl <- asl (DP)  // get next byte (and bit7 of it in tc)

		if_f_t(in_f(tc_to_f, to_t, ld, acc_t, t_fill_2_sh4,nop ), in_t(tc_to_f,to_t,ld,acc_t,t_fill_1_sh4,nop) );   //   F0: pix7, BG  F1: pix7, FG
		if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0: pix6, BG  F1: pix6, FG

		ins6(nop, to_t, ld_ir, acc_t, t_label2,page_blit ); // jp back to loop
		ins6(irq_to_f, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the two pixels

		/* 6-10-2025 old
		no_f_write_error = 1;
		ins6(tc_to_f,to_dpl,asl,acc_t,dpl,nop); // dpl <- asl(dpl),  f <- tc

		// the dpl shift register is empty. take the last pixel from the next dpl byte
		ins6(nop,to_t,inc,acc_t,t_txt_lsb,nop); // T <- inc (t_txt_lsb <- T) 
		ins6(nop,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T 	
		ins6(nop,to_dpl,or,acc_t,lit0,nop); // dpl <- T	
		ins6(nop, to_dpl, ld, acc_t, ext, nop ); // dpl <- (DP)  // get next byte

		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3, page_blit ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   //   F0: jp exit  F1: (pc++)<-T, F<-tc
		no_f_write_error = 0;

		if_f_t(in_f(tc_to_f, to_t, ld, acc_t, t_fill_2_sh4,nop ), in_t(tc_to_f,to_t,ld,acc_t,t_fill_1_sh4,nop) );   //   F0: pix7, BG  F1: pix7, FG
		if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0: pix6, BG  F1: pix6, FG

		ins6(nop, to_t, ld_ir, acc_t, t_label2,page_blit ); // jp back to loop

		ins6(irq_to_f, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the two pixels
		*/
	}

	if ( (act == act_loop) && (op_name =="T") && (ma != "U"  ))  // copy text. Aligned.
	{	
		// F=0  interrupt, F <- 1                F=1  no interrupt
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  F0: jp int, F1: dec A
		no_f_write_error = 1;
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   // F0:  nop,  F1: dpl <- asl(dpl),  f <- tc
		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   //   F0: jp exit  F1: (pc++)<-T, F<-tc
		no_f_write_error = 0;

		if_f_t(in_f(tc_to_f, to_t, ld, acc_t, t_fill_2_sh4,nop ), in_t(tc_to_f,to_t,ld,acc_t,t_fill_1_sh4,nop) );   //   F0: pix7, BG  F1: pix7, FG
		if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0: pix6, BG  F1: pix6, FG

		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the two pixels
	
		var i=3;  // pixels 5,4 and 3,2 and 1,0.
		while (i != 0)
		{	ins6(nop, to_a, sub, acc_a, lit1, nop); // dec A
			no_f_write_error = 1;
			ins6(tc_to_f,to_dpl,asl,acc_t,dpl,nop); // dpl <- asl(dpl),  f <- tc
			
			if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3, page_blit ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   //   F0: jp exit  F1: (pc++)<-T, F<-tc
			no_f_write_error = 0;

			if_f_t(in_f(tc_to_f, to_t, ld, acc_t, t_fill_2_sh4,nop ), in_t(tc_to_f,to_t,ld,acc_t,t_fill_1_sh4,nop) );   //   F0: pix7, BG  F1: pix7, FG
			if_f_t(in_f(nop, to_t, or, acc_t, fill_2, nop ), in_t(nop,to_t,or,acc_t, fill_1, nop) );   //   F0: pix6, BG  F1: pix6, FG

			ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the two pixels
			i = i-1;
		}
		/* old
		ins6(nop,to_t,inc,acc_t,t_txt_lsb,nop); // T <- inc (t_txt_lsb <- T) 
		ins6(nop,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T 	
		ins6(nop,to_dpl,or,acc_t,lit0,nop); // dpl <- T	

		ins6(nop, to_t, ld_ir, acc_t, t_label2,page_blit ); // jp back to loop
		ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop ); // dpl <- (DP)  //next byte
		*/ 

		// 2-10-2025 new. increment source-msb when needed
		ins6(nop,to_t,inc,acc_t,t_txt_lsb,nop); // T <- inc (t_txt_lsb <- T) 
		ins6(tc_to_f,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T 	
		ins6(nop,to_dpl,or,acc_t,lit0,nop); // dpl <- T	

		// F=0  normal, to loop (label2).  F=1  when dpl++ had carry, increment dph		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label2,page_blit ), in_t(nop, to_dph, inc, acc_t, t_save_dph, nop)); // F0: jp loop, F1: dph <- inc
	  
	    if_f_t(in_f(irq_to_f,to_dpl, ld, acc_t, ext, nop ), in_t(nop, to_t, inc, acc_t, t_save_dph, nop)   );   //  F0: dpl <- (DP) ,  F1: (pc++)<-T, F<-tc

		ins6(nop, to_mem, ld, acc_t, t_save_dph, nop );
		ins6(nop, to_t, ld_ir, acc_t, t_label2,page_blit );
	
		ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop );		

	}
	if ( (act == act_last_corr) && (op_name =="T") )  // text last correction. 
	{	ins6(nop,to_dpl,asl,acc_t,dpl,nop) ;   //  dpl <- asl(dpl)   get the last pixel. pixel in high nibble must be replaced

		ins6(tc_to_f, to_t, ld, acc_t, pc_lin_ind, bank0);  // get current (pc)
		ins6(nop, to_t, and, acc_t, reg_0F, nop); //  f <- tc, clear upper nibble	
	
		if_f_t(in_f(nop, to_t, or, acc_t, t_fill_2_sh4, nop ), in_t(nop,to_t,or,acc_t, t_fill_1_sh4, nop) );   //   F0:  BG hi nibble  F1:  FG hi nibble		
	
		ins6(irq_to_f, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the old and new pixels, inc pc, irq_to_f				
		
		ins6(nop, to_t, ld_ir, acc_t, t_label5, page_blit); // jump to label 5
		ins6(nop, to_t, xor, acc_t, lit0, nop);  // nop, delay
	}


	// -------  action: COPY24  -------  2-1-2025

	// copies from 2-bits-per-pixel to 4-bits-per-pixel

	if ( (act == act_prepare_loop) && (op_name =="2") )  // prepare copy24
	{	ins6(nop,to_t,ld,acc_t,dpl,nop); // T <- dpl
		ins6(nop,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T  save dpl
		
		ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2
		ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop ); // dpl <- (DP)  //first byte  (in delay)
	}
	if ( (act == act_first_corr) && (op_name =="2") )  // first corr copy24
	{	ins6(nop,to_t,ld,acc_t,dpl,nop); // T <- dpl
		ins6(nop,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T  save dpl
		
		ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2		
		ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop );  // dpl <- (DP)  //first byte  (in delay)
	}	
	if ( (act == act_loop) && (op_name =="2") )  // copy 2 bit to 4 bit
	{	
		// F=0  interrupt, F <- 1                F=1  no interrupt
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  F0: jp int, F1: dec A
		no_f_write_error = 1;
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   // F0:  nop,  F1: dpl <- asl(dpl),  f <- tc

		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   //   F0: jp exit  F1: (pc++)<-T, F<-tc
		no_f_write_error = 0;
		
		// 16-3-2025 try colors
		// following 2 instructions construct the first 4-bit pixel from 2 bits. Use the shift-4 colors.
		if_f_t(in_f(tc_to_f, to_t, ld, acc_t, lit0,nop ), in_t(tc_to_f,to_t,ld,acc_t,t_fill_1_sh4,nop) );   //   F0: 0, black   F1: fill1
	
		if_f_t(in_f(nop,to_t,xor,acc_t,t_fill_2_sh4, nop ), in_t(nop, to_t, or, acc_t, lit0, nop) );   // 16-3  F0: xor fill2 		  F1: nop
		// now handle next 2 bits for the following pixel
		// not decrement A: ins6(nop, to_a, sub, acc_a, lit1, nop); // dec A.  if it reaches 0, we stop.
		no_f_write_error = 1;
		ins6(h_to_f,to_dpl,asl,acc_t,dpl,nop); // dpl <- asl(dpl),  f <- tc ( no, do: f <- h )
		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3, page_blit ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   //   F0: jp exit  F1: (pc++)<-T, F<-tc
		no_f_write_error = 0;
		// following 2 instructions construct the second 4-bit pixel from 2 bits
		// use XOR instead of OR or ADD, because we want to do tc_to_f at the same time
		if_f_t(in_f(tc_to_f, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f,to_t,xor,acc_t,fill_1,nop) );   //   F0: 0, black   F1: fill1
	
		if_f_t(in_f(nop,to_t,xor,acc_t,fill_2, nop ), in_t(nop, to_t, or, acc_t, lit0, nop) );   // 16-3  F0: xor fill2  F1: nop
	
		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the first two 4-bit pixels

		// now handle next 2 bits for the following pixel
		ins6(nop, to_a, sub, acc_a, lit1, nop); // dec A.  if it reaches 0, we stop.
		no_f_write_error = 1;
		ins6(tc_to_f,to_dpl,asl,acc_t,dpl,nop); // dpl <- asl(dpl),  f <- tc
		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3, page_blit ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   //   F0: jp exit  F1: (pc++)<-T, F<-tc
		no_f_write_error = 0;
		// following 2 instructions construct the third 4-bit pixel from 2 bits
		if_f_t(in_f(tc_to_f, to_t, ld, acc_t, lit0,nop ), in_t(tc_to_f,to_t,ld,acc_t,t_fill_1_sh4,nop) );   //   F0: 0, black   F1: fill1
		// 16-3-2025 if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop ), in_t(nop,to_t,xor,acc_t, t_fill_2_sh4, nop) );   //   F0: nop    F1: xor fill2 
		if_f_t(in_f(nop,to_t,xor,acc_t,t_fill_2_sh4, nop ), in_t(nop, to_t, or, acc_t, lit0, nop) );   // 16-3   F0:  xor fill2  F1: nop

		// now handle next 2 bits for the last of the 4 pixels
		// not decrement A: ins6(nop, to_a, sub, acc_a, lit1, nop); // dec A.  if it reaches 0, we stop.
		no_f_write_error = 1;
		ins6(h_to_f,to_dpl,asl,acc_t,dpl,nop); // dpl <- asl(dpl),  f <- tc ( no, do: f <- h )
		if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3, page_blit ), in_t(tc_to_f,to_dpl,asl,acc_t,dpl,nop) );   //   F0: jp exit  F1: (pc++)<-T, F<-tc
		no_f_write_error = 0;
		// following 2 instructions construct the fourth 4-bit pixel from 2 bits
		if_f_t(in_f(tc_to_f, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f,to_t,xor,acc_t,fill_1,nop) );   //   F0: 0, black   F1: fill1
		// 16-3  if_f_t(in_f(nop, to_t, or, acc_t, lit0, nop ), in_t(nop,to_t,xor,acc_t, fill_2, nop) );   //   F0: nop    F1: xor fill2 
		if_f_t(in_f(nop,to_t,xor,acc_t,fill_2, nop ), in_t(nop, to_t, or, acc_t, lit0, nop) );   // 16-3  F0: xor fill2  F1:nop

		ins6(nop, to_mem, ld, acc_t, pc_lin_pp, bank0);  // store the last two 4-bit pixels

		// prepare for next source byte. Same as for TEXT
		ins6(nop,to_t,inc,acc_t,t_txt_lsb,nop); // T <- inc (t_txt_lsb <- T) 
		ins6(nop,to_mem,ld,acc_t,t_txt_lsb,nop); // t_txt_lsb <- T 	
		ins6(nop,to_dpl,or,acc_t,lit0,nop); // dpl <- T	
		ins6(nop, to_t, ld_ir, acc_t, t_label2,page_blit ); // jp back to loop
		ins6(irq_to_f, to_dpl, ld, acc_t, ext, nop ); // dpl <- (DP)  //next byte

		// 27 cycles

	}
	if ( (act == act_last_corr) && (op_name =="2") )  // copy24 last correction. no action here yet
	{	ins6(nop, to_t, ld_ir, acc_t, t_label5, page_blit); // jump to label 5
		ins6(nop, to_t, xor, acc_t, lit0, nop);  // nop, delay
	}


	// -------  action: SAVE  -------  12-1-2025

	if ( (act == act_prepare_loop) && (op_name =="V") )  // prepare save
	{	ins6(nop, to_a, sub, acc_a, lit1, nop);  // 22-3-2025  correction for one byte too much in loop
		
		ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit); // jump to label 2
	
		ins6(irq_to_f, to_t, ld, acc_t, pc_lin_pp, nop ); // T <- (PC++)  //first byte  (in delay)
	}
	if ( (act == act_first_corr) && (op_name =="V") )  // first corr save
	{	ins6(nop, to_a, sub, acc_a, lit1, nop);  // 22-3-2025  correction for one byte too much in loop
	   
		// new 9-4-2025:      took code from "C" and changed it.
	    // what should it do:
		//  T <- (pc_lin_pp)  *
		//  T <- T and 0F  // clear upper
		//  reg_vga_acc <- T  // save result
		//  T <- (dp)    *
		//  T <- T res 0F  // clear lower
		//  T <- T or reg_vga_acc  // result
		//  ... store at (DP) ??   *
		// inc DP
		// T <- DP  // irq_to_f, go to loop

		// 22-3-2025A  first correction. High nibble always transparent.
		
		ins6(irq_to_f, to_t, ld, acc_t, pc_lin_pp, nop ); // get source data from screen	9-4-2025	
		ins6(nop,to_t,and,acc_t,reg_0F,nop); // clear high nibble, will be transparent
		ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop); // save it. There will be no vga interrupt before we use this, so it's ok.
		
		ins6(nop, to_t, ld, acc_t, ext, nop ); // get mem databuffer contents	9-4-2025

		ins6(nop,to_t,res2,acc_t,reg_0F,nop); // clear low nibble, becomes color 0
			                                    
		ins6(nop,to_t,or,acc_t,reg_vga_acc,nop);  // combination of both nibbles
	
		// 5-5-2025	  handle cy when dpl overflows

		ins6(nop, to_mem, ld, acc_t, ext, nop ); // store at (dp)		9-4-2025	
		ins6(nop, to_dpl, inc, acc_t, dpl, nop);    // and increment source pointer   <--- What if there is a CY ? goes wrong !
													// But the application (Symbos)	can make sure that DPL is never near cy area. (250424A)
		
		ins6(tc_to_f, to_t, ld, acc_t, pc_lin_pp, nop ); // T <- (PC++)  //first byte  // 24-4-2025  must be PC++ !

	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label2, page_blit), in_t(nop, to_dph, inc, acc_t, t_save_dph, nop)); // f0: goto lbl2  f1: cy=1 inc dph
 
		ins6(irq_to_f, to_t  , inc, acc_t, t_save_dph, nop);  // for c=0, this is a delay slot	8-5-2025 added irq_to_f	

		ins6(nop, to_t, ld_ir, acc_t, t_label2, page_blit);  // jp to the copy function

	    ins6(irq_to_f, to_mem, ld, acc_t, t_save_dph, nop); // store dph  (in delay)
		// 5-5-2025 end
	}	
	if ( (act == act_loop) && (op_name =="V") )  // save loop.
	{
		// 27-12-2024 (for copy)
		//   F0: jp int      F1: dec A
		//       delay           (dph/dpl)<-T, F<-tc
		//       jp label3       dpl++
		//       delay           F<-tc 
		//       jp label2       dph <- inc(t_save_dph)
		//       T<-(PC++),F<-irq  T <- inc(t_save_dph) 
		//                       t_save_dph <- T
		//                       jp label2
		//                       T<-(PC++),F<-irq
			
		// F=0  interrupt, F <- 1                F=1  no interrupt, (pc++) <- T  Uses linear PC mode !
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, BLIT_IRQ, page_blit), in_t(nop, to_a, sub, acc_a, lit1, nop)); //  jp int, F1: dec A
	  
		// 26-1-2025 next line, no bank 0 for 'ext' !!
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_mem, ld, acc_t, ext, nop ) );   //   nop,  F1: (dph/dpl)<-T, F<-tc
	
		// F=0  count reached zero. to label 3.  F=1  dpl++		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label3,page_blit ), in_t(nop, to_dpl, inc, acc_a, dpl, nop)); //  jp exit, F1: inc dpl
	    if_f_t(in_f(nop, to_t, xor, acc_t, lit0,nop ), in_t(tc_to_f, to_t, xor, acc_t, lit0, nop) );   //   nop,  F1: nop, F<-tc

		// F=0  normal, to loop (label2).  F=1  when dpl++ had carry, increment dph		
	    if_f_t(in_f(nop, to_t, ld_ir, acc_t, t_label2,page_blit ), in_t(nop, to_dph, inc, acc_t, t_save_dph, nop)); //  jp loop, F1: dph <- inc
	  
	    if_f_t(in_f(irq_to_f, to_t, ld, acc_t, pc_lin_pp, nop ), in_t(nop, to_t, inc, acc_t, t_save_dph, nop)   );   //   nop,  F1: (pc++)<-T, F<-tc

		ins6(nop, to_mem, ld, acc_t, t_save_dph, nop );
		ins6(nop, to_t, ld_ir, acc_t, t_label2,page_blit );
	
		ins6(irq_to_f, to_t, ld, acc_t, pc_lin_pp, nop );		

		// 6 cycles per transferred byte

	}
	if ( (act == act_last_corr) && (op_name =="V") )  // save last correction.
	{
		// new  9-4-2025   got code from "C" and changed that
		 // what should it do:
		//  T <- (pc_lin)  *
		//  T <- T res2 0F  // clear lower
		//  reg_vga_acc <- T  // save result
		//  T <- (dp)  *
		//  T <- T and 0F  // clear upper
		//  T <- T or reg_vga_acc  // result
		//  ... store at (dp) ??  *
		// 
		//   // irq_to_f, go to label5

		ins6(nop, to_dpl, inc, acc_a, dpl, nop);  //  added 8-5-2025 
		ins6(nop, to_dph, inc_tc, acc_t, t_save_dph, nop); // 8-5-2025 if cy, inc dph

		// 9-4-2025  last correction.
		
		ins6(nop, to_t, ld, acc_t, pc_lin_ind, nop ); // get source data	  9-4-2025, 8-5-2025 remove irq_to_f
		ins6(nop,to_t,res2,acc_t,reg_0F,nop); // clear low nibble
		ins6(nop, to_mem, ld, acc_t, reg_vga_acc, nop); // save it. There will be no vga interrupt before we use this, so it's ok.
		
		ins6(nop, to_t, ld, acc_t, ext, nop ); // get databuffer contents	  9-4-2025 	
		ins6(nop,to_t,and,acc_t,reg_0F,nop); // clear high nibble
			                                    
		ins6(nop,to_t,or,acc_t,reg_vga_acc,nop);  // combination of both nibbles
		
		ins6(nop, to_t, ld_ir, acc_t, t_label5, page_blit);  // jp to end of line
			
		ins6(nop, to_mem, ld, acc_t, ext, nop ); // store at (dp)	 9-4-2025 		

	}



	print_cycles();	
}





function blit_actions(opc,op_name)   // generate 8 different actions for this opcode
{ blit_action(opc + act_loop,op_name);
  blit_action(opc + act_prepare_loop,op_name);
  blit_action(opc + act_first_corr,op_name);  
  blit_action(opc + act_last_corr,op_name);
  blit_action(opc + act_unalign + act_loop,op_name);
  blit_action(opc + act_unalign + act_prepare_loop,op_name);
  blit_action(opc + act_unalign + act_first_corr,op_name);  
  blit_action(opc + act_unalign + act_last_corr,op_name);
}


//-------------------------------------------
//
//      ISETTA  RESET
//
//-------------------------------------------


// specific Isetta functions


function isetta_reset(page, opc, name) {
	opcode_page(page, opc, name, nop, nop);

	// 14-11-2023 remove literals
	no_f_write_error = 1;
	ins6(irq_to_f, to_a, inc_acc, acc_a, lit0, nop);  // start with a NOP (increment ACC) // 2-12 irq_to_f

	ins6(nop, to_t, zero, acc_t, lit0, nop);	// set t to 0 
	ins6(nop, h_to_sw_vdu_n, ld, acc_t, lit0, nop);   // 5-3-2024 VDU/ signal high to enable CPU
	ins6(nop, to_t, inc_acc, acc_t, lit0, nop);	// inc t

	ins6(nop, to_t,h_to_sw_spi_cs1_n, acc_t, lit0, nop); // cs1/ (onboard flash)	inactive  31-3-2025
	ins6(nop, to_t,h_to_sw_spi_cs2_n, acc_t, lit0, nop); // cs2/ (uSD card)	inactive  31-3-2025	

	ins6(nop, to_mem, ld, acc_t, reg_x, nop);	// store T (0x01) in reg_x // 7-9 here

	ins6(nop, to_t, zero, acc_t, lit0, nop);			// set T to 0  16-4-2024

	ins6(nop, to_pch, ld_acc, acc_t, lit0, nop);		// 14-11 set pch to 0 ( pch <- T)													

	// now initialize table counters, and go to isetta_tbl1

	ins6(nop, to_dpl, zero, acc_t, lit0, nop);	// set dpl to 0 
	ins6(nop, to_a, dec_acc, acc_t, lit0, nop);	// 14-11-2023 set A to FF,  A <- dec(T)

	// 30-10-2024 ins6(nop, to_t, ld_ir, acc_t, reg_x, page_reset);  // go to opcode 0x01 (was 0x11) in reset page

	ins6(nop, to_t, ld_ir, acc_t, reg_x, page_z80_ix);  // go to opcode 0x01 (was 0x11) in reset page. 30-11-2024 TBL1 in page_ix

	// 24-6-2025  ins6(nop, to_dph, zero, acc_t, lit0, nop);	// 7-9-2023 set dph to 0  2-12 upd_f
	ins6(nop, to_dph, ld, acc_t, reg_x, nop);  // 24-6-2025  move SHR table. move 1 to dph

	// 5-3-2024 put the current date in the microcode.
	micro_pc = micro_pc | 0x000E; // select the last position of this opcode, timestamp will be at 0x00001E

	timestamp = (dec2bcd(thisyear - 2000) << 16) + (dec2bcd(thismonth) << 8) + dec2bcd(thisday);

	if_f_t(timestamp, timestamp);
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

function isetta_tbl1(page, opc, name)    // initialize shift-right table, 0x11  14-11 move to 0x01
{
	opcode_page(page, opc, name, nop, nop);

	// 24-6-2025  for zero-page, use 'dir'. For SHR table use 'ext'
	ins6(irq_to_f, to_mem, ld, acc_t, dir, bank1);		// move from T to mem (shr table), old shr table
	ins6(nop, to_mem, ld, acc_t, ext, bank2); // 24-6-2025 new shr table, bank2, 0x0100	

	ins6(nop, to_a, inc_acc, acc_a, lit0, nop);	 	// 14-11-2023 inc A

	ins6(nop, to_mem, ld, acc_a, dir, bank2);	    // 14-11-2023 write A to bank2 (identity table)
	ins6(nop, to_mem, ld, acc_a, dir, bank0);	    // 30-10-2024 write A to bank0 (identity table)

	ins6(nop, to_dpl, inc_acc, acc_a, lit0, nop);	// dpl<-A+1

	ins6(nop, to_mem, ld, acc_t, dir, bank1);		// move from T also to next mem pos (shr table) 7-9, old shr table
	ins6(nop, to_mem, ld, acc_t, ext, bank2); // 24-6-2025 new shr table, bank2, 0x0100	

	ins6(nop, to_t, inc_acc, acc_t, lit0, upd_n);		// T <- T + 1  22-7 upd_n

	ins6(nop, to_a, inc_acc, acc_a, lit0, upd_z);	 	// 14-11-2023 inc A  2-12 upd_f
	ins6(n_to_f, to_mem, ld, acc_a, dir, bank2);	// 14-11-2023 write A to bank2 (identity table)
	ins6(nop, to_mem, ld, acc_a, dir, bank0);	    // 30-10-2024 write A to bank1 (identity table)	


	// if F flag is 0, bit7 was zero and we repeat the loop at TBL1

	// 30-10-2024 TBL1 is now at address 1 in page_ix	
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, lit1, page_z80_ix), // goto 0x01 (stored in reg_x)
		in_t(nop, to_a, add, acc_t, lit0, nop));	

	ins6(nop, to_dpl, inc_acc, acc_a, lit0, nop);	// dpl<-A+1 in delay. dpl now incremented by 2

	// at the end of the loop, T happens to be 0x80... 

	ins6(nop, to_mem, ld, acc_t, reg_128, nop);	  // 7-9 initialize reg_128 to 0x80

	// 30-10-2024  define shift-right values of literals 8, 32 and 40
	ins6(nop, to_dpl, ld, acc_a, lit8, nop);
	ins6(nop, to_a, shr, acc_a, dir, nop); // get shifted value (bank 1)
	ins6(nop, to_mem, ld, acc_a, lit4, nop);	 //  8 >> 1 = 4
	ins6(nop, to_dpl, ld, acc_a, lit32, nop);
	ins6(nop, to_a, shr, acc_a, dir, nop); // get shifted value
	ins6(nop, to_mem, ld, acc_a, lit16, nop);	 //  32 >> 1 = 16
	ins6(nop, to_dpl, ld, acc_a, lit40, nop);
	ins6(nop, to_a, shr, acc_a, dir, nop); // get shifted value
	ins6(nop, to_mem, ld, acc_a, lit20, nop);	 //  40 >> 1 = 20

	// 30-10-2024  Initialize bank register with appl=1, bank=3
	ins6(nop, to_a, dec, acc_t, lit0, nop);	 // A <- FF
	ins6(nop, to_a, sub, acc_a, lit4, nop);  // A <- A -4; A = 1111 1011
	ins6(nop, to_a, res2, acc_a, lit8, nop); // new 17-11-2025, reset bit 3	(A19=0)
	ins6(nop, to_bnk, add, acc_a, lit0, nop); // also writes dph. uses acc_a.

	// 6-3-2024
	// go to the builder of the values, instruction 0x16
	ins6(nop, to_a, ld, acc_t, lit20, nop);  // val 20 (hex 0x14)
	ins6(nop, to_dpl, add_1, acc_a, lit1, nop);	// add 1+cy to get 22 (hex 0x16)

	ins6(nop, to_a, ld, acc_t, lit0, nop); // for building the values, set A=0

	ins6(nop, to_t, ld_ir, acc_t, dpl, page_reset);  // go to specified instruction
	ins6(nop, to_dpl, inc, acc_t, lit1, nop); // for building the values, set DPL=2

	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

// Isetta go_proc new 4-3-2024	
function isetta_go_proc(page, opc, name)    
// jp to one of the implemented processors
// in Z80 mode, if the F flag is set, a jump to the RST #38 instruction is done (frame interrupt)
// 
{   // 24-11-2024 for opcode ISA_BLIT this function is defined in the blitter.
	opcode_page(page, opc, name, nop, nop);
	var target;
	if (opc == ISA_6502) target = page_6502;  // G6502
	else if (opc == ISA_Z80) target = page_z80    // GZ80
	else alert("isetta_go_proc unknown processor " + hexstring2(opc));

	if (opc == ISA_Z80)
    {  //     F = 0                                            F = 1  (yes it was FF, do interrupt)
		if_f_t(in_f(nop,to_t,ld_ir,acc_t,pc_pp,target), in_t(nop, to_t, dec, acc_t,reg_irq, nop)); // clr RQST bit (bit0), new reg_irq value is FE
				
  		if_f_t(in_f(delay_m, nop, nop, nop, nop, nop),  in_t(h_to_f, to_t, ld_ir, acc_t, reg_irq, page_z80)); // place FF in IR. Do h_to_f, no irq_to_f	10-3-2025
						
		// 27-2-2025 the following line is wrong, it should be conditional ? No it is never reached when F=0.
		ins6(nop, to_mem, ld, acc_t, reg_irq, nop);   // write new reg_irq value
	} 
	else
	{ ins6(nop, to_t, ld_ir, acc_t, pc_pp, target);
	  ins6(delay_m, nop, nop, nop, nop, nop);
	}
	print_cycles();
}

function isetta_go(page, opc, name)    // jp to the processor currently set in reg_isa
{
	opcode_page(page, opc, name, nop, nop);
	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset);
	ins6(nop, to_t, ld, acc_t, lit0, nop);  // no irq to F  2-10-2024
	print_cycles();
}


//-------------------------------------------
//
//            I/O instructions
//
//-------------------------------------------


// Functions of the I/O ports

// the register ports start at 0x10 up to 0x1F (skipping 0x19)
// can continue at 0x30 up to 0x3F skipping 0x34, 0x35, 0x36 and 0x39

function in_reg(opc, register)   //  IN port ; where port is an internal register
{
	opcode_page(page_in, opc, 'in_reg', register, nop);
	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp back to current isa
	ins6(nop, to_a, ld, acc_t, register, nop);  // move the SW register to ACC
	print_cycles();
}

function out_reg(opc, register)   // OUT port ; where port is an internal register
{
	opcode_page(page_out, opc, 'out_reg', register, nop);
	ins6(nop, to_mem, ld, acc_a, register, nop);  // move ACC to the SW register (do not do this 
	// in delay slot, new reg_isa must be used)
	// 2-10-2024 clr F	
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp back to current isa // 6-10 l_to_f
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f
	print_cycles();
}

// 11-7-2024 out_isa  // this is an explicit output register that causes a switch to another processor
function out_isa(opc)   // OUT port ; where port is 0x0A (6502), 0x0B(Z80) or 0x0C..0x0F (future processors)
{
	opcode_page(page_out, opc, 'out_isa', nop, nop);

    if (opc == 0x0A)
		{ ins6(nop, to_t, ld,  acc_t, lit40, nop);  // lit40 + lit16 = 56(dec) = 0x38 (isa_6502)
		  ins6(nop, to_t, add, acc_t, lit16, nop);
		}
	else if (opc == 0x0B)
		{ ins6(nop, to_t, inc, acc_t, lit40, nop);  // (lit40+1) + lit16 = 57(dec) = 0x39 (isa_Z80)
		  ins6(nop, to_t, add, acc_t, lit16, nop);
		}

	else error_msg("processor not supported: ",nop)

	ins6(nop, to_mem, ld, acc_t, reg_isa, nop);  // move T to the reg_isa register
	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f
	print_cycles();
}

function in_const(opc, value)   //  IN port ; 2-10-2024 Return a constant value (used for microcode year-month-day)
{
	opcode_page(page_in, opc, 'in_const', nop, nop);
	make_literal(to_a,value);
	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp back to current isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f
	print_cycles();
}


function inout_reg(opc, register)  // generate both a read and write instruction for this register
{
	in_reg(opc, register); // generate input (read) instruction
	out_reg(opc, register); // generate output(write) instruction
}


function inout_zx_spectrum(opc)   // port FE for input and output (port_io_zx_spectrum)
{ 	opcode_page(page_in, opc, 'in_zx_spectrum', nop, nop);  // input, for Z80 only. It does a CALL to a certain address

    ins6(nop, to_dpl, ld, acc_a, lit4, nop);        // reg_user_zx_kb    addr 0004 in bank 4
	ins6(nop, to_t, ld, acc_a, dir, bank4); 	// get high dst addr to T, from (dpl), reg_user_zx_kb in bank 4
	ins6(nop, to_dpl, ld, acc_a, lit0, nop); // 13-11 get low dst addr to dpl, always 0

	ins6(nop, to_t, ld_ir, acc_t, lit4, page_z80_ix);   // jump to CALR  (call-routine)
	ins6(nop, to_mem, ld, acc_t, reg_th, nop); // 	save in temp reg_th	
	print_cycles();

	opcode_page(page_out, opc, 'out_zx_spectrum', nop, nop);  // output port FE, for speaker and border color.
   /*
   - reg_speaker <- A
   - T <- AND (A, lit8)  // isolate 2nd voice. A should not be changed !
   - T <- T + reg_speaker  // add bit3, now have 00,0x10 or 0x20. 0x10 being neutral.
   - T <- T + 0x80     // now have 0x80, 0x90, 0x100
   - T <- T - lit8   
   - T <- T - lit8     // now have 0x70, 0x80, 0x90
   - reg_speaker <- T
   --------------------------------
    20-6-2024
   - reg_speaker <- A  ; store sample

   - T <- asl(lit8)
   - T <- add(T,lit8) ; now have 0x18 as mask

   - T <- and(T,reg_speaker)  ; input is masked now, result in A. 00,10,08,18 

   - reg_speaker <- T
   - T <- asl(reg_speaker) ;  00 20 10 30

   - T <- T + 0x80     // now have  80 90 A0 B0
   - T <- T - lit32    //  60 70 80 90     
   - T <- T + lit8     //  68 78 88 98
   - reg_speaker <- T   
  */
	ins6(nop, to_mem, ld, acc_a, reg_speaker, nop); // reg_speaker <- A (just temporary)
	ins6(nop, to_t, asl, acc_t, lit8, nop); //  T <- lit16 0x10
	ins6(nop, to_t, add, acc_t, lit8, nop); //  T <- T + lit8	 T = 0x18
	ins6(nop, to_t, and, acc_t, reg_speaker, nop); //  input is masked now, result in A. 00,10,08,18 

	ins6(nop, to_mem, ld, acc_t, reg_speaker, nop); // reg_speaker <- T 
	ins6(nop, to_t, asl, acc_t, reg_speaker, nop); // *2 :  00 20 10 30

	ins6(nop, to_t, add, acc_t, reg_128, nop);	//  T <- T + 0x80     // now have  80 90 A0 B0
	ins6(nop, to_t, sub, acc_t, lit32, nop);    //  60 70 80 90    	             
	ins6(nop, to_t, add, acc_t, lit8, nop);	//  T <- T - lit8     //  68 78 88 98
	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp back to current isa
	
	ins6(nop, to_mem, ld, acc_t, reg_speaker, nop); // 	save T in reg_speaker // 2-10-2024 no irq_to_f
	print_cycles();
}

function in_gen_input(opc)   // port_in_gen_input   read parallel input port
{ 	opcode_page(page_in, opc, 'in_general', nop, nop);

	ins6(irq_to_f, to_mem, inp, acc_t, reg_tl, nop);	// write reg_tl with 'input' instruction
	ins6(nop, to_a, ld, acc_a, reg_tl, nop);    // put result in A

	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f	
	print_cycles();
}


// 25-7-2024  manipulate output bits. Needed to send commands to the PS/2 keyboard 
// 27-11-2024 and to PS/2 mouse

function out_bit(opc)   // OUT port , set/clr the output bit according to CY
{	opcode_page(page_out, opc, 'out_bit', nop, nop);

 	if (opc == port_out_sw_exx ) // Use CY to select one of the two Z80 register banks
		{ ins6(nop, c_to_sw_exx, ld, acc_a, lit0, nop);  }

	else if (opc == port_out_sw_vdu_n )  // 27-11-2024 // Use CY to set VDU/ on or off
		{ ins6(nop, c_to_sw_vdu_n, ld, acc_a, lit0, nop);  }

	else if (opc == port_out_setup ) // 8-12-2024 renamed to setup
		{
		    // 8-12-2024  set SETUP high

			ins6(nop, h_to_sw_exx, ld, acc_t, lit0, nop);	// set SW_EXX to 1

			// The SETUP will be high until the vga screen is activated.
			// give a first pulse on IRQ FF to have it in the same state at the end
			// set T to 15, will set lowest sound output bits high (done by wr_sound)

			ins6(nop, to_t, ld, acc_t, reg_0F, nop); 		
			ins6(nop, h_to_sw_wr_sound_n, ld, acc_t, lit0, nop);  // wr_sound/ HIGH 
			ins6(nop, to_t, ld, acc_t, reg_0F, nop); 			
			
			ins6(nop, l_to_sw_wr_sound_n, ld, acc_t, lit0, nop);	// wr_sound/ LOW  18-5-2025 was not low !
			ins6(nop, to_t, ld, acc_t, reg_0F, nop); 			
	
			// set the IRQ signal (same as sound_wr), and give a low-going pulse on vdu_n

			ins6(nop, h_to_sw_wr_sound_n, ld, acc_t, lit0, nop);  // wr_sound/ HIGH 
			ins6(nop, l_to_sw_vdu_n , ld, acc_t, lit0, nop);  // vdu/ low 
			ins6(nop, to_t, ld, acc_t, reg_0F, nop); 			
			ins6(nop, h_to_sw_vdu_n , ld, acc_t, lit0, nop);  // vdu/ high
			 
			ins6(nop, l_to_sw_wr_sound_n, ld, acc_t, lit0, nop);	// wr_sound/ LOW  18-5-2025 was not low !			
			
		}
	else if (opc == port_out_sound_imm ) // 11-12-2024 immediate output A to sound port
		{ 		  				
			// need to give two pulses on IRQ, to prevent generating an extra interrupt.
			// But a single interrupt can go wrong when IRQ falls exactly in this function
			// Therefore, it should only be used when video is not active (yet).

			ins6(nop, to_t, ld, acc_a, lit0, nop); 
			ins6(nop, h_to_sw_wr_sound_n, ld, acc_a, lit0, nop);  // wr_sound/ HIGH 
			ins6(nop, to_t, ld, acc_a, lit0, nop); 			
			ins6(nop, l_to_sw_wr_sound_n, ld, acc_a, lit0, nop);	// wr_sound/ LOW
			ins6(nop, to_t, ld, acc_a, lit0, nop); 			
	
			// set the IRQ signal (same as sound_wr), and give a low-going pulse on vdu_n

			ins6(nop, h_to_sw_wr_sound_n, ld, acc_a, lit0, nop);  // wr_sound/ HIGH 
			
			ins6(nop, to_t, ld, acc_a, lit0, nop); 			
			
			ins6(nop, l_to_sw_wr_sound_n, ld, acc_a, lit0, nop);	// wr_sound/ LOW 
			
		}		
  
	else error_msg("function out_bit, unknown operand: ",opc)

	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f	
	print_cycles();
}	



// for writing/reading ACC to/from another memory bank, addressed by HL
/*
	const port_io_bank0 = 0xF0  // 16-11-2024
	const port_io_bank1 = 0xF1  // 12-5-2024	
	const port_io_bank2 = 0xF2  // 12-5-2024		
	const port_io_bank3 = 0xF3  // 12-5-2024	
	const port_io_bank4 = 0xF4  // 12-5-2024	
	const port_io_bank5 = 0xF5  // 12-5-2024	
	const port_io_bank6 = 0xF6  // 12-5-2024	
	const port_io_bank7 = 0xF7  // 12-5-2024

	inout_bank(opcode,bank)		
*/

function inout_bank(opc,mybank)
  { // generate input instruction, to read from a certain bank
    opcode_page(page_in, opc, 'in_bank', mybank, nop);
	ins6(nop, to_dph, ld, acc_t, reg_h, nop);  // 29-10-2024 change acc_a to acc_t
	ins6(nop, to_dpl, ld, acc_a, reg_l, nop); 	
	ins6(nop, to_a, ld, acc_a, ext, mybank); 	  // ld a,(hl) from selected bank

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp back to current isa // 6-10 l_to_f
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 6-10  no delay_m
	print_cycles();
    // generate output instruction, to write to a certain bank
    opcode_page(page_out, opc, 'out_bank', mybank, nop);
	ins6(nop, to_dph, ld, acc_t, reg_h, nop); // 29-10-2024 change acc_a to acc_t
	ins6(nop, to_dpl, ld, acc_a, reg_l, nop); 	
	ins6(nop, to_mem, ld, acc_a, ext, mybank); 	  // ld (hl),a  to selected bank
	
	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f	
	print_cycles();
  }


// read ZX Spectrum Joystick, port 0x1F.  15-6-2024.

function in_zx_joystick(opc)   // port_in_gen_input   read parallel input port
{ 	opcode_page(page_in, opc, 'in_zx_joystick', nop, nop);


	ins6(nop, to_a, ld, acc_a, lit0, nop);    // set A to 0, joystick inactive

	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f		
	print_cycles();
}

// read scancode from keyboard. The code comes from a buffer that was filled in interrupt code.
// It is also used to read bytes that come from the Raspberry Pi

function in_kb(opc)   //  IN port ; Get (in ACC) scancode from keyboard or ASCII from RPi, with Z=0.
// On return, Z flag is set if no char was pressed. In that case, ACC=0.
// If FF was received, also return Z=1 and ACC=0.
{
	opcode_page(page_in, opc, 'in_kb', nop, nop);
	ins6(nop, to_t, ld, acc_t, reg_kb_ptin, nop);
	ins6(nop, to_t, xor, acc_t, reg_kb_ptout, nop); 	 // compare ptin and ptout
	ins6(nop, to_mem, ld, acc_t, reg_z, nop); 	     // result to Z register. If 0, then Z=1, buffer empty
	ins6(nop, to_t, dec_acc, acc_t, lit0, nop);   // set TC if buffer not empty
	ins6(tc_to_f, to_dpl, ld, acc_t, reg_kb_ptout, nop);    // move TC to F, ptout to dpl
	ins6(nop, to_dph, ld, acc_t, lit32, nop);  // address 0x20pp  (pp = ptout)	30-6-2025

	//           F=0  buffer empty                            F=1  buffer not empty
	if_f_t(in_f(nop, to_a, ld, acc_a, lit0, nop), in_t(nop, to_a, ld, acc_a, ext, bank1)); // F=0  acc=0   F=1 get char
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_kb_ptout, nop)); // F=0:  null, F=1 get inc. pt
	if_f_t(in_f(nop, to_t, inc, acc_t, lit0, nop), in_t(nop, to_dpl, inc_acc, acc_a, lit0, nop)); // F=0: set TC=0, F=1: 19-4-2024 check if FF received, by adding 1
    // TC=1 when FF received, put it in the F flag
	if_f_t(in_f(tc_to_f, to_t, ld, acc_t, lit0, nop), in_t(tc_to_f, to_mem, ld, acc_t, reg_kb_ptout, nop)); // F=0:  null  F=1 store pt
    // now, when F=1, set received byte to 00 and set Z flag
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_a, ld, acc_a, lit0, nop)); // F=1: A <- 0
	if_f_t(in_f(irq_to_f, to_t, inc, acc_t, lit0, nop), in_t(irq_to_f, to_mem, ld, acc_a, reg_z, nop)); // F=1: reg_z <- A

	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f	
	print_cycles();
}


// 27-11-2024 read scancode from mouse. The code comes from a buffer that was filled in interrupt code.

function in_mouse(opc)   //  IN port ; Get byte from ps/2 mouse
// On return, Z flag is set if no code was present. In that case, ACC=0.
// Not for mouse: If FF was received, also return Z=1 and ACC=0.
{
	opcode_page(page_in, opc, 'in_mouse', nop, nop);
	ins6(nop, to_t, ld, acc_t, reg_mouse_ptin, nop);
	ins6(nop, to_t, xor, acc_t, reg_mouse_ptout, nop); 	 // compare ptin and ptout
	ins6(nop, to_mem, ld, acc_t, reg_z, nop); 	     // result to Z register. If 0, then Z=1, buffer empty
	ins6(nop, to_t, dec_acc, acc_t, lit0, nop);   // set TC if buffer not empty
	ins6(tc_to_f, to_dpl, ld, acc_t, reg_mouse_ptout, nop);    // move TC to F, ptout to dpl
	ins6(nop, to_dph, ld, acc_t, lit1, nop);  // address 0x01pp  (pp = ptout)

	// 27-11-2024 for mouse, banknumber changed from 1 to 0
	//           F=0  buffer empty                            F=1  buffer not empty
	if_f_t(in_f(nop, to_a, ld, acc_a, lit0, nop), in_t(nop, to_a, ld, acc_a, ext, bank0)); // F=0  acc=0   F=1 get char
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_mouse_ptout, nop)); // F=0:  null, F=1 get inc. pt
	if_f_t(in_f(nop, to_t, inc, acc_t, lit0, nop), in_t(nop, to_dpl, inc_acc, acc_a, lit0, nop)); // F=0: set TC=0, F=1: 19-4-2024 check if FF received, by adding 1

	// TC=1 when FF received, put it in the F flag. For mouse, just used to store the ptout pointer.
	if_f_t(in_f(tc_to_f, to_t, ld, acc_t, lit0, nop), in_t(tc_to_f, to_mem, ld, acc_t, reg_mouse_ptout, nop)); // F=0:  null  F=1 store pt

	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f	
	print_cycles();
}


// write TX byte to GP_OUT1 with sync serial protocol  16-4-2024

function out_tx(opc)   //  OUT port ;  Write ACC to character output, to RPi
// On return, Z flag is set (and ACC set to 0) if the buffer was full, and the byte was not written
{
	opcode_page(page_out, opc, 'out_tx', nop, nop);
	// first check if the buffer is full: add 1 to input pt and see if it equals output pt
	ins6(nop, to_t, inc, acc_t, reg_tx_ptin, nop);
	ins6(nop, to_t, xor, acc_t, reg_tx_ptout, nop); 	 // compare ptin and ptout
	ins6(nop, to_mem, ld, acc_t, reg_z, nop); 	     // result to Z register. If 0, then Z=1, buffer is full

	ins6(nop, to_t, dec_acc, acc_t, lit0, nop);   // clear TC if buffer is full
	ins6(tc_to_f, to_dpl, ld, acc_t, reg_tx_ptin, nop);    // move TC to F, pt-in to dpl
	ins6(nop, to_dph, inc, acc_t, lit1, nop);  // address 0x02pp  (pp = ptout)

	//           F=0  buffer full                            F=1  buffer not full
	
	if_f_t(in_f(nop, to_a, ld, acc_a, lit0, nop), in_t(nop, to_mem, ld, acc_a, ext, bank0)); // F=0  acc=0   F=1 write char	30-6-2025 bank0 now

	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_tx_ptin, nop)); // F=0:  null  F=1 get inc. pt

	if_f_t(in_f(irq_to_f, to_t, ld, acc_t, lit0, nop), in_t(irq_to_f, to_mem, ld, acc_t, reg_tx_ptin, nop)); // F=0:  null  F=1 store pt

	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f		
	print_cycles();
}

function out_shutdn(opc) // 30-6-2025  port 0x1C.
{ 	opcode_page(page_out, opc, 'out_shutdn', nop, nop);

	// input A=0 : reset,  A= 0x01 : shutdown

	ins6(nop,to_t,and_tst,acc_a,lit1,nop); // test bit 0
	ins6(tc_to_f, to_t, ld, acc_t, lit0, nop); // nop, tc_to_f

	if_f_t(in_f(nop, l_to_sw_pc17, ld, acc_t, lit0, nop),   // if false, set pc17 low  18-8-2025
				in_t(nop, to_t, ld, acc_t, lit0, nop)); // if true, 0x01, nop, continue
	if_f_t(in_f(nop, l_to_sw_pc18, ld, acc_t, lit0, nop),   // if false, set pc18 low  18-8-2025
				in_t(nop, to_t, ld, acc_t, lit0, nop)); // if true, 0x01, nop, continue

	if_f_t(in_f(l_to_f, to_t, ld_ir, acc_t, lit0, page_reset),   // if false, 0x00, RESET
				in_t(nop, to_t, ld, acc_t, lit0, nop)); // if true, 0x01, nop, continue

	// 0x01, SHUTDN.  

	// Set PWR led OFF, by making IRQ_ACK high.
	
	ins6(nop, h_to_sw_wr_sound_n, ld, acc_t, lit0, nop);  // wr_sound/ HIGH . 

	ins6(nop,to_t,ld,acc_t,lit0,nop); // T <- 0
	ins6(nop,to_mem,ld,acc_t,reg_kb_state,nop); // bit7=0 indicates shutdown	 
	
	make_literal(to_t, rtc_shutdn); // put opcode in T
	ins6(nop,to_dpl,add,acc_t,lit0,nop);  // move to DPL

	ins6(nop, to_t, ld_ir, acc_t, dpl, page_rtc); // jp to rtc_shutdn, that's an endless loop that counts time and date
	ins6(nop,to_t,add,acc_t,lit0,nop); // nop

	// the shutdown command switches LED off and enters an infinite loop (where only RTC is counting)

	print_cycles();
}

function out_sound_direct(opc) // 5-3-2024
{
	opcode_page(page_out, opc, 'out_sound_dir', nop, nop);
	// An output instruction to write directly to the sound register. It will also toggle the 
	// IRQ flag, so if the video display is active, the monitor might temporary loose 
	// synchronization.
	// Normally, writing to the sound register is done directly after every line interrupt, and
	// it will at the same time clear the interrupt request by toggling the IRQ flipflop.
	// The byte value to write is in ACC   
	// The WR_SOUND/ is also used to reset the IRQ.
	// A short HIGH pulse on WR_SOUND/ will reset (actually toggle) the IRQ
	// Therefore, the default for WR_SOUND/ is LOW.

	// 5-12-2024 the value in ACC will be written to the sound register at the next HW interrupt (and the following ones).
	ins6(nop, to_mem, ld, acc_a, reg_sound, nop);  // 5-12-2024

	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f		
	print_cycles();
}


// SPI bus functions

	// I/O ports for SPI bus transactions

//	out_spi_wr(port_spi1_out);  // 0x32 Output one byte to spi1
//	out_spi_wr(port_spi2_out);  // 0x37 Output one byte to spi2
//	in_spi_rd(port_spi_in);     // 0x3A Input one byte from prev selected SPI port
//	out_spi_idle(port_spi_idle); // 0x3F Close SPI transaction

/* 22-10-2024 new SPI ports definition
0x32 port_spi1_start
0x33 port_spi2_start
0x37 port_spi_out
0x3A port_spi_in
0x3F port_spi_idle

new: spi_clkh (microcode signal, shares position with upd_n)

SPI_START:
  - set clk high
  - set CS low (CS1 or CS2)
  - set clk low
SPI WRITE  :  for each bit:
  - get bit-to-write from transmit register into CY
  - set clk high (this will clock the bit into the SPI device)
  - set clk low
SPI READ:  for each bit:
  - set clk high (shortly after this, bit will appear on MISO)
  - set clk low, and shift the bit into the receive register  
*/

// 22-10-2024
// This intermediate function will also work with the old HW.
// It outputs the SPI clock both on ctl_upd_n and on the '259
// The input (MISO) is still connected in the old way, through the input register

function out_spi_start(opc) // 26-4-2024  start, can be called for SPI1 or SPI2	
  {     
     cs_select = l_to_sw_spi_cs1_n;
	 if (opc == port_spi1_start)
	    opcode_page(page_out, opc, 'spi1', nop, nop);
     else { opcode_page(page_out, opc, 'spi2', nop, nop);		
             cs_select = l_to_sw_spi_cs2_n; 
			 // 31-3-2025 new code, longer clock pulse. The databit should be don't care.
			 // for 250331B, removed the spi_clkh from these.
			i = 5;
		
			ins6(nop,to_t, cs_select, acc_a, lit0, nop);  //  CS2 low, clock still high (31B not high)
			i = 7;
		
			ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
			ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f		
    		print_cycles();  
			return;
	      }
  
	// but for now, also use the old clock signal:
	
	// 6-4-2025 changed clock from spi_clkh to spi1_clkh

	// Here it starts, set clock high
	ins6(nop,to_t , ld, acc_a, lit0, spi1_clkh);  // clock HIGH
    	
	ins6(nop,to_t, cs_select, acc_a, lit0, spi1_clkh);  // CS1 or CS2 low (active) 4-12-2024

	// 4-12-2024 disable the Z80 RST #38 interrupt during SPI transactions.
	
	ins6(nop,to_t,ld,acc_t,lit32, spi1_clkh); // T <-32  28-3-2025  let clock stay high a little bit longer
    ins6(nop,to_t,res,acc_t,reg_irq, nop);    // T <- T res reg_irq (reset bit T in reg_irq)
	ins6(nop,to_mem,ld,acc_t,reg_irq, nop); 

	// since l_to_sw_spi_cs1_n is a latch, it will become low half-way the cycle, while the clk will stay
	// high until the end of the cycle.
	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f		
    print_cycles();  
  }

/*
SPI WRITE  :  for each bit:
  - get bit-to-write from transmit register into CY
  - set clk high (this will clock the bit into the SPI device)
  - set clk low
*/

function out_spi_wr(opc) // 26-4-2024  Write, (same for spi1 and spi2)	
  { 
	if (opc == port_spi_out_bit) // 30-3-2025 added.  THere is room for 32 cycles.
	  {  opcode_page(page_out, opc, 'spi_wr_bit', nop, nop);
		// during initialization, max clock speed on SPI is 400 kHz (25 cycles). So the high-time is no less than 13 cycles .
		i = 7;
	    while (i >= 0)
		  { ins6(nop, to_t, add, acc_a, reg_128, nop);  // put databit (acc bit 7) in DTC bit
		    i--;
		  }
		i = 13;
	    while (i >= 0)
		  { ins6(nop, to_t, add, acc_a, reg_128, spi2_clkh);  // put databit (acc bit 7) in DTC bit, and have clock bit high. 6-4-2025 use spi2_clkh
		    i--;
		  }
		i = 7;
	    while (i >= 0)
		  { ins6(nop, to_t, add, acc_a, reg_128, nop);  // put databit (acc bit 7) in DTC bit
		    i--;
		  }
		ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
		ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f	

		print_cycles();  // this will be around 26 cycles. Ignore error msg.
		return
	  }

	if (opc == port_spi2_out) // 6-4-2025 added.  There is room for 32 cycles.
	  { //opcode_page(page_out, opc, 'spi2_wr_bit', nop, nop);
	    opcode_page(page_out, opc, 'spi2_out', nop, nop); // 7-8-2026
		ins6(nop, to_dpl, xor, acc_a, lit0, nop); 		  // DPL <- A	
		i = 7;
		while (i >= 0)  // do this 8 times, bit 7, 6 ... 1, 0.
		{ 
			// but for now, also use the old clock signal:
			ins6(nop, to_dpl, asl, acc_t, dpl, upd_c);   // shift DPL left, bit7 to CY. clock goes LOW (or is low)

			// 4-11-2024:
			ins6(nop, to_t, ld, acc_a, lit0, nop);  // NOP, let CY be valid before next clk edge, old clk low
			ins6(nop, to_t, ld, acc_a, lit0, spi2_clkh);  // clock HIGH  This clocks CY into device SPI_MOSI		6-4-2025 spi2_clkh		

			i = i - 1;
		}	

		// 2-10-2024 clr F
		ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
		ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f	

		print_cycles();  // this will be around 26 cycles. Ignore error msg.
		return
	  }

	  
	// 22-10-2024
	opcode_page(page_out, opc, 'spi_wr', nop, nop); 
    ins6(nop, to_dpl, xor, acc_a, lit0, nop); 		  // DPL <- A	
	i = 7;
	while (i >= 0)  // do this 8 times, bit 7, 6 ... 1, 0.
	  {
		// but for now, also use the old clock signal:
        ins6(nop, to_dpl, asl, acc_t, dpl, upd_c);   // shift DPL left, bit7 to CY. clock goes LOW (or is low)
		// 4-11-2024:
		ins6(nop, to_t, ld, acc_a, lit0, nop);  // NOP, let CY be valid before next clk edge, old clk low
        ins6(nop, to_t, ld, acc_a, lit0, spi1_clkh);  // clock HIGH  This clocks CY into device SPI_MOSI		6-4-2025 spi1_clkh	
        //ins6(nop, to_t, ld, acc_a, lit0, spi1_clkh);  // 22-8-2025 extra clock HIGH (datasheet: duty cycle must be approx 50%)
														// But the extra clock makes this instruction too long !!
		i = i - 1;
	  }	
	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f	

    print_cycles();  // this will be around 26 cycles. Ignore error msg.
  }

/*
SPI READ:  for each bit:
  - set clk high (shortly after this, bit will appear on MISO)
  - set clk low, and shift the bit into the receive register  
*/

function in_spi_rd(opc) // 26-4-2024  Read, no need to specify SPI1 or SPI2	
  {  
    if (opc == port_spi_in_bit)  // 30-3-2025
	  { opcode_page(page_in, opc, 'spi_in_bit', nop, nop); // input single bit from MISO. No clocking.

 		ins6(nop, to_dpl, ld, acc_a, lit0, nop); // set dpl to 0

        ins6(nop, to_t, add, acc_a, lit0, nop);  // The MISO bit will go to flag F. Needs group 1 instruction: add

		ins6(nop, to_dpl, rol_miso, acc_t, dpl, nop);    // shift DPL left, the new MISO bit into bit0. prev instr must be group1.		                                                

		ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
		ins6(nop, to_a, ld, acc_a, dpl, nop); 		    //  A <- DPL. result: MISO is acc bit 0. Other acc bits are zero. 

		print_cycles();   // 
		return;
	  }

	if (opc== port_spi2_in)  // 3-4-2025
	  { 	opcode_page(page_in, opc, 'spi2_in', nop, nop);
		    i = 7;
	  	    ins6(nop, to_a, dec, acc_t, lit0, nop);  // A <- 255,  help providing HIGH to MOSI (unused)
	  		// will have to read the MISO before the clock. The read-data and clockpulse can be in the same cycle !
			while (i >= 0)  // do this 8 times, bit 7, 6 ... 1, 0.
			{	ins6(nop, to_t, add, acc_a, reg_128, nop);    // instr must be group1.	The DTC carry will be send to the SPI device (but not used)		
				// 6-4-2025 use spi2_clk
				ins6(nop, to_dpl, rol_miso, acc_t, dpl, spi2_clkh); 1 // clk HIGH The MISO bit (from prev cycle) will go to flag F. Needs group 1 there: add
				i = i - 1;
			}
			ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
			ins6(nop, to_a, ld, acc_a, dpl, nop); 		    //  A <- DPL
			print_cycles();   // this will be around 42 cycles. (Now 18 !) Ignore error msg.
			return;
	  }
	
	if (opc== port_spi2_in_fast)  // 11-5-2025
	  { 	opcode_page(page_in, opc, 'spi2_in_fast', nop, nop);

	  	    ins6(nop, to_a, dec, acc_t, lit0, nop);  // A <- 255,  help providing HIGH to MOSI (unused)

			// first bit: allow interrupt
			ins6_chi(nop, to_t, add, acc_a, reg_128, nop);    // instr must be group1.	The DTC carry will be send to the SPI device (but not used)		
			
			ins6_pcmin2(nop, to_dpl, rol_miso, acc_t, dpl, spi2_clkh); 1 // clk HIGH The MISO bit (from prev cycle) will go to flag F. Needs group 1 there: add

	  		// will have to read the MISO before the clock. The read-data and clockpulse can be in the same cycle !
		    i = 5;			
			while (i >= 0)  // do this 6 times, bit 6 ... 1.
			{	ins6(nop, to_t, add, acc_a, reg_128, nop);    // instr must be group1.	The DTC carry will be send to the SPI device (but not used)		
				// 6-4-2025 use spi2_clk
				ins6(nop, to_dpl, rol_miso, acc_t, dpl, spi2_clkh); 1 // clk HIGH The MISO bit (from prev cycle) will go to flag F. Needs group 1 there: add
				i = i - 1;
			}
			// for the last bit, result to A
			ins6(nop, to_t, add, acc_a, reg_128, nop);    // instr must be group1.	The DTC carry will be send to the SPI device (but not used)		
			// 6-4-2025 use spi2_clk
			ins6(nop, to_a, rol_miso, acc_t, dpl, spi2_clkh); 1 // clk HIGH The MISO bit (from prev cycle) will go to flag F. Needs group 1 there: add
			// 
			ins6(to_dpl,ld,acc_t,reg_l,nop);  // dpl <- L
			ins6(to_dph,ld,acc_t,reg_h,nop);  // dph <- H

			// inc HL

			ins6(nop, to_t, inc, acc_t, reg_l, nop); // inc L
			ins6(tc_to_f, to_mem, ld, acc_t, reg_l, nop); // store incremented L register

			if_f_t(in_f(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset),   // if false, no carry, next
													in_t(nop, to_t, inc, acc_t, reg_h, nop)); // if true, inc H
			if_f_t(in_f(nop,to_mem,ld,acc_a,ext,nop),   // if false, no carry, store byte in delay
													in_t(nop,to_mem,ld,acc_a,ext,nop)); // if true, store byte

			ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset);
			ins6(nop, to_mem, ld, acc_t, reg_h, nop); // store incremented H

			print_cycles();   // this will be around 23 cycles. Ignore error msg.
			return;
	  }

	opcode_page(page_in, opc, 'spi_in', nop, nop);
    // 3-11-2024 new SPI data input method
	i = 7;
	while (i >= 0)  // do this 8 times, bit 7, 6 ... 1, 0.
	  { //ins6(nop, l_to_sw_spi_clk, ld, acc_a, lit0, nop);  // clock LOW 
	    //  22-10-2024 added spi_clkh in next 2 instructions   
		// set clk high (shortly after this, bit will appear on MISO)    
		// 6-4-2025 use spi1_clk
        ins6(nop, to_t, add, acc_a, lit0, spi1_clkh);  // clock HIGH  The MISO bit will go to flag F. Needs group 1 instruction: add      
		ins6(nop, to_dpl, rol_miso, acc_t, dpl, nop);    // shift DPL left, the new MISO bit into bit0. prev instr must be group1.
		i = i - 1;
	  }

	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_a, ld, acc_a, dpl, nop); 		    //  A <- DPL

     print_cycles();   // this will be around 42 cycles. (Now 18 !) Ignore error msg.
  }

function out_spi_idle(opc) // 26-4-2024  Write, can be called for SPI1 or SPI2	
  { 
    opcode_page(page_out, opc, 'spi_idle', nop, nop);

    ins6(nop, h_to_sw_spi_cs1_n, ld, acc_a, lit0, nop);  // CS1 high
	ins6(nop, h_to_sw_spi_cs2_n, ld, acc_a, lit0, nop);  // CS2 high  re-inserted 4-12-2024

	// 4-12-2024 re-enable the Z80 RST #38 interrupt after SPI transactions.
	// Note that, if interrupts were also disabled with DI, that will stay in effect (acts on another bit in reg_irq)
	ins6(nop,to_t,ld,acc_t,lit32, nop); // T <-32
    ins6(nop,to_t,or,acc_t,reg_irq, nop);    // T <- T OR reg_irq (set bit T in reg_irq)
	ins6(nop,to_mem,ld,acc_t,reg_irq, nop); 

	// 2-10-2024 clr F
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to new isa
	ins6(nop, to_t, ld, acc_t, lit0, nop); // 2-10-2024 no irq_to_f		
     print_cycles(); 
  }

  
function in_spi_state(opc) // 10-2-2025  SPI status input port, returns Z=1 if SPI busy
  {  
	opcode_page(page_in, opc, 'spi_state', nop, nop);
	ins6(nop,to_t,ld,acc_t,lit32, nop); // T <-32
    ins6(nop,to_t,and,acc_t,reg_irq, nop);    // T <- T AND reg_irq (test bit T in reg_irq)
	
	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp to isa
	ins6(nop, to_mem, ld, acc_t, reg_z, nop); // write test result to Z register	

    print_cycles();
  }	


//-------------------------------------------
//
// 8-4-2024  Device drivers
//
//-------------------------------------------

// The device drivers are 'called' during the horizontal line interrupt.
// Each driver is active for a very short period, then passes control to the next driver.



// First driver: KB and TX.  PS/2 Keyboard and Raspberri Pi communication
//
// It is a synchronous protocol. The Raspbery Pi or keyboard delivers the clock.

// uses: reg_kb_bitbuf  // kb device: keyboard input, or data from Raspberry Pi
//       reg_kb_state
//       reg_kb_ptin
//       reg_kb_ptout
// uses: reg_tx_bitbuf  // tx device: data to Raspberry Pi (clocked by kb clock)
//       reg_tx_ptin
//       reg_tx_ptout
//       reg_tx_state

// There is a KB buffer and a TX buffer.
// When the ptin==ptout, the buffer is empty.
// Writing to a buffer, write at ptin* and then increment ptin (wraparound at end)
// Reading from a buffer, first read at ptout* and then increment ptout (wraparound at end)

// The instruction for reading a keyboard bit is reached by jumping to an instruction that is
// stored in reg_kb_state.

// The states are instructions that describe the actions of that state. 
// Most states each time wait until the clock gets low, then does action and goes to the next state
// States that end with 'E' wait until the clock gets high, do an action and go to the next state.

// These KB / TX instructions will be in the reset page

const KB_STATE_WAIT = 0x81  // wait for startbit
const KB_STATE_WAITE = 0x82
const KB_STATE_BIT0 = 0x83
const KB_STATE_BIT0E = 0x84
const KB_STATE_BIT1 = 0x85
const KB_STATE_BIT1E = 0x86
const KB_STATE_BIT2 = 0x87
const KB_STATE_BIT2E = 0x88
const KB_STATE_BIT3 = 0x89
const KB_STATE_BIT3E = 0x8a
const KB_STATE_BIT4 = 0x8b
const KB_STATE_BIT4E = 0x8c
const KB_STATE_BIT5 = 0x8d
const KB_STATE_BIT5E = 0x8e
const KB_STATE_BIT6 = 0x8f
const KB_STATE_BIT6E = 0x90
const KB_STATE_BIT7 = 0x91
const KB_STATE_BIT7E = 0x92
const KB_STATE_PAR = 0x93 // read parity bit
const KB_STATE_PARE = 0x94

const SOUND_STATE_IDLE = 0x95 // PSG sound
const SOUND_STATE_ZX   = 0x9B // 1-9-2025  ZX Spectrum/Apple-2 sound

const KB_NEXT_DRIVER = reg_mouse_state;  // 8-12-2024 (E) device driver to run after the kb/tx

/* 29-9-2025
// io_kb_get: Subroutine for the KB states  ( 6 cycles )
function io_kb_get()   // 8-4-2024  subroutine, generate code to get clock in F and input data (inverted) in TC
{  // the two input bits come from the parallel input port
	ins6(nop, to_mem, inp, acc_t, reg_kb_tmp, nop);  // read parallel input, put in temp-low register reg_kb_tmp
	// data KB_IN at bit 6  and clk KB_CLK at bit 3
	make_bitmask(to_t, 3);  // bitmask bit 3, KB_CLK
	ins6(nop, to_t, and, acc_t, reg_kb_tmp, nop); // select bit3 of input
	ins6(nop, to_t, dec_acc, acc_t, lit0, nop);   // use the special 'decrement_accumulator' for accumulator T
	// this will leave TC set to 1 if the clock input was 1
	no_f_write_error = 1;
	ins6(tc_to_f, to_t, asl, acc_t, reg_kb_tmp, nop);  // put TC (clock) in F, load input byte and shift it left (databit in bit7)
	// The above line may generate an error because it is group1 but also writes F. So we use "no_f_write_error".

	ins6(nop, to_t, add, acc_t, reg_128, nop);  	// 15-4-2024 Add 128, so bit7 will go to TC												
}
*/

// 29-9-2025 a shorter function for io_kb_get. 2 cycles less.

function io_kb_get()   // 8-4-2024  subroutine, generate code to get clock in F and input data (inverted) in TC
{  // the two input bits come from the parallel input port
	ins6(nop, to_mem, inp, acc_t, reg_kb_tmp, nop);  // read parallel input, put in temp-low register reg_kb_tmp

	ins6(nop, to_t, asl, acc_t, reg_kb_tmp, nop);  // bit7 <- data , bit4 <- clock

	ins6(nop, to_dpl, and_tst, acc_t, lit16, nop); // test bit 4, result in tc, dpl unused.

	no_f_write_error = 1;
	ins6(tc_to_f, to_t, add, acc_t, reg_128, nop);  	// 15-4-2024 Add 128, so bit7 will go to TC												
}


// Here come the instructions for reading the keyboard RX. It also handles the TX debugging char output (to the RPi)

// each io_kb instruction must have the same amount of cycles !

// The keyboard input buffer uses addresses 0x020xx in bank1 (256 positions)
// The debugging output buffer uses addresses 0x02xx in bank1 (256 positions)

/* TX
At the beginning, a byte is pulled from the buffer:
   ld dpl,txbufpt
   ld dph,1
   ld t,(dph|dpl)
   t <- or (t,tx_state) // make it FF when buffer empty
   st txbitbuffer.t
*/

function io_kb_startbit(opc)   // wait until the clock gets low
{
	opcode_page(page_reset, opc, 'io_kb_startbit', nop, nop); // 
	io_kb_get();

	//  F = 0 clock low, go to next state        F = 1 clock still high, stay in this state 
	//  but data must be low !! 
	//  Keyboard RX: Move TC to F. If the startbit is not low, we stay in this state.
	if_f_t(in_f(tc_to_f, to_t, ld, acc_t, lit0, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: move TC to F  

    // TX function, new here 18-4-2024. Get a byte from the TX buffer:
	ins6(nop, to_dpl, ld, acc_t, reg_tx_ptout, nop);
	ins6(nop, to_dph, inc, acc_t, lit1, nop);      // address 0x02pp  (pp = ptout)	
	ins6(nop, to_t, ld, acc_t, ext,bank0);         // get byte from buffer memory in bank 0 !!	 30-6-2025 bank0 now
	ins6(nop, to_mem, ld, acc_t, reg_tx_bitbuf, nop);	   // write to bit buffer	

    // 11-5-2024 add fillers to get to 0x10 cycles

	ins6(null_m, nop, nop, nop, nop, nop); // 2 extra cycles
	ins6(null_m, nop, nop, nop, nop, nop);

	// go to next state or stay in this state
	if_f_t(in_f(nop, to_t, inc, acc_t, reg_kb_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, KB_NEXT_DRIVER, page_reset);
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_kb_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: and store it back	
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

function io_kb_startbit_end(opc)   // wait until the clock gets high
{
	opcode_page(page_reset, opc, 'io_kb_startbit_end', nop, nop); // 
	io_kb_get();
	//       F = 0 clock low, stay in same state        F = 1 clock high, go to next state        
	//  

	// output TX. Check the buffer. When the buffer is empty, the byte becomes FF so it sends an FF byte.

	// new here, check if buffer empty:
	ins6(nop,to_t,ld,acc_t,reg_tx_ptin,nop);
    ins6(nop,to_t,xor,acc_t,reg_tx_ptout,nop);	 // xor pt-in and pt-out
    // build a mask 255 or 0
	ins6(nop,to_t,dec_acc,acc_t,lit0,nop);    // inc T. buffer empty -> TC=0     non-empty -> TC=1
	ins6(nop,to_t,dec_tc,acc_t,lit0,nop);     //  empty: input TC=0, T <- 255   non-empty: input TC=1,  T <-0 
	
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_tx_state, nop)); // F=1: 19-4-2024 write to TX_STATE

	// the result, 0 or FF, is or'ed with the bitbuffer
	ins6(nop, to_t, or, acc_t, reg_tx_bitbuf,nop);  // if FF, buffer is empty, send FF byte. else (0): buffer non-empty
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_tx_bitbuf, nop)); // F=1:  write to bit buffer

	// go to next state or stay in this state                      
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_kb_state, nop)); // F=1:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, KB_NEXT_DRIVER, page_reset);
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_kb_state, nop)); // F=1: and store it back
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

function io_kb_databit(opc)   // wait until the clock gets low
{
	opcode_page(page_reset, opc, 'io_kb_databit', nop, nop); // 
	io_kb_get();
	// When the clock is low, the data can be read.
	//    F = 0 clock low, go to next state             F = 1 clock still high, stay in this state
	//    
	// Keyboard RX   Shift received data bit (TC) into reg-kb_bitbuf    
	if_f_t(in_f(nop, to_t, rol_tc, acc_t, reg_kb_bitbuf, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: Shift into bit buffer
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_kb_bitbuf, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: and store it back

	// output TX
	if_f_t(in_f(nop, to_t, asl, acc_t, reg_tx_bitbuf, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: Shift bit out of buffer
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_tx_bitbuf, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: and store buffer back	
	/* 24-1-2026
	if_f_t(in_f(nop, dtc_to_sw_gp_out1, ld, acc_t, lit0, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: write bit DTC to GP_OUT1
	*/
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(null_m, nop, nop, nop, nop, nop)); // 24-1-2026	not write to serial, thats a19 now

    // 11-5-2024 add fillers to get to 0x10 cycles
 
	ins6(null_m, nop, nop, nop, nop, nop); // 2 extra cycles
	ins6(null_m, nop, nop, nop, nop, nop);

	// go to next state or stay in this state
	if_f_t(in_f(nop, to_t, inc, acc_t, reg_kb_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, KB_NEXT_DRIVER, page_reset);
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_kb_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: and store it back	
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

/* TX, per bit:  (as done in io_kb_databit)
   ld T,(txbitbuffer<<1)  
   st (txbitbuffer),t 
   write gp_out1,h/l  // h/l choice comes from DTC
*/

function io_kb_databit_end(opc)   // wait until the clock gets high
{
	opcode_page(page_reset, opc, 'io_kb_databit_end', nop, nop); // 
	io_kb_get();
	//    F = 0 clock low, stay in same state, waiting       F = 1 clock high, go to next state      
	//   

    // 11-5-2024 add fillers to get to 0x10 cycles. Was 9 cycles, so add 7.

	ins6(null_m, nop, nop, nop, nop, nop); // 7 extra cycles
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop); 
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop); 
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop); 
			
	// go to next state or stay in this state
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_kb_state, nop));  // F=1:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, KB_NEXT_DRIVER, page_reset);
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_kb_state, nop)); // F=1: and store it back
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

function io_kb_databit_end_last(opc)   // wait until the clock gets high. Special version for end of last databit
{
	opcode_page(page_reset, opc, 'io_kb_databit_end_last', nop, nop); // 
	io_kb_get();

	// write KB data to the buffer. Also when still waiting for clock, but in that case the bufferpt won't be incremented yet.
	ins6(nop, to_dpl, ld, acc_t, reg_kb_ptin, nop);	
	ins6(nop, to_dph, ld, acc_t, lit32, nop);  // address 0x20pp  (pp = ptin)	30-6-2025
	ins6(nop, to_t, ld, acc_t, reg_kb_bitbuf, nop);
	ins6(nop, to_mem, ld, acc_t, ext, bank1);		 // write to memory in bank 1 !!

	ins6(null_m, nop, nop, nop, nop, nop); // 3 extra cycles  to get from D (13) to 10 (16)
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);

	//    F = 0 clock low, stay in same state, waiting       F = 1 clock high, go to next state      
	//       
	// go to next state or stay in this state                       
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_kb_state, nop));  // F=1:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, KB_NEXT_DRIVER, page_reset);
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_kb_state, nop)); // F=1: and store it back
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}


function io_kb_paritybit(opc)   // wait until the clock gets low
{
	opcode_page(page_reset, opc, 'io_kb_paritybit', nop, nop); // 
	io_kb_get();

	//    F = 0 clock low, go next state          F = 1 clock still high, stay in this state

	// output TX. Check if the buffer is empty, result in reg_tx_state

    // 11-5-2024 add fillers to get to 0x10 cycles. Was 9 cycles, so add 7.

	ins6(null_m, nop, nop, nop, nop, nop); // 7 extra cycles
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop); 
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop); 
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop); 

	// go to next state or stay in this state
	if_f_t(in_f(nop, to_t, inc, acc_t, reg_kb_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, KB_NEXT_DRIVER, page_reset);
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_kb_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: and store it back	
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}


function io_kb_paritybit_end(opc)   // wait until the clock gets high
{
	opcode_page(page_reset, opc, 'io_kb_paritybit_end', nop, nop); // 
	io_kb_get();
	//    F = 0 clock low, stay in same state, waiting       F = 1 clock high, go to next state (that's the first state, KB_STATE_WAIT)     
	//                                                                                    
    // Keyboard RX
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_kb_ptin,nop)); // F=1:  get incremented kb_ptin
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_kb_ptin,nop)); // F=1: and store it back	

    // output TX. inc the output pointer, except when buffer is empty.
    ins6(nop,to_t,inc,acc_t,reg_tx_state,nop) //  empty: 255 -> T.bit0=0   full: 0 -> T.bit0=1  (the INC toggles bit0)
	ins6(nop,to_t,and,acc_t,lit1,nop);        // result is 0  or 1
	ins6(nop,to_t,add,acc_t,reg_tx_ptout,nop); // inc buffer_out pointer, but leave it the same if buffer is empty
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_tx_ptout,nop)); // pointer store back into memory

	ins6(null_m, nop, nop, nop, nop, nop); // one extra cycle to get to 10 cycles

	// go to next state or stay in this state
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_128, nop)); // F=1: state: KB_STATE_WAIT 
	ins6(nop, to_t, ld_ir, acc_t, KB_NEXT_DRIVER, page_reset);
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_kb_state, nop)); // F=1: and store it
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

//********  mouse driver  ***********

const MOUSE_STATE_WAIT = 0xd0  // wait for startbit
const MOUSE_STATE_WAITE = 0xd1
const MOUSE_STATE_BIT0 = 0xd2
const MOUSE_STATE_BIT0E = 0xd3
const MOUSE_STATE_BIT1 = 0xd4
const MOUSE_STATE_BIT1E = 0xd5
const MOUSE_STATE_BIT2 = 0xd6
const MOUSE_STATE_BIT2E = 0xd7
const MOUSE_STATE_BIT3 = 0xd8
const MOUSE_STATE_BIT3E = 0xd9
const MOUSE_STATE_BIT4 = 0xda
const MOUSE_STATE_BIT4E = 0xdb
const MOUSE_STATE_BIT5 = 0xdc
const MOUSE_STATE_BIT5E = 0xdd
const MOUSE_STATE_BIT6 = 0xde
const MOUSE_STATE_BIT6E = 0xdf
const MOUSE_STATE_BIT7 = 0xe0
const MOUSE_STATE_BIT7E = 0xe1
const MOUSE_STATE_PAR = 0xe2 // read parity bit
const MOUSE_STATE_PARE = 0xe3

const MOUSE_NEXT_DRIVER = reg_sound_state;  // device driver to run after the mouse

/* 29-9-2025
// io_mouse_get: Subroutine for the MOUSE states  ( 6 cycles )
function io_mouse_get()   // 27-11-2024  subroutine, generate code to get clock in F and input data (inverted) in TC
{  // the two input bits come from the parallel input port
	// For mouse, the input port was already read.
	//ins6(nop, to_mem, inp, acc_t, reg_kb_tmp, nop);  // read parallel input, put in temp-low register reg_kb_tmp

	// data KB_IN at bit 6  and clk KB_CLK at bit 3
	// 27-11-2024 data MOUSE_IN at bit 2  and clk MOUSE_CLK at bit 1
	make_bitmask(to_t, 1);  // bitmask bit 1, MOUSE_CLK
	ins6(nop, to_t, and, acc_t, reg_kb_tmp, nop); // select bit1 of input
	ins6(nop, to_t, dec_acc, acc_t, lit0, nop);   // use the special 'decrement_accumulator' for accumulator T
	// this will leave TC set to 1 if the clock input was 1
	
	// for mouse:
	ins6(tc_to_f, to_t, ld, acc_t, lit4, nop); // bitmask, bit2 0000 0100, and tc -> F
	ins6(nop, to_t, and, acc_t, reg_kb_tmp, nop); // select bit2 of input
	ins6(nop, to_t, dec_acc, acc_t, lit0, nop);   // use the special 'decrement_accumulator' for accumulator T
	// this will leave TC set to 1 if the data input was 1
}
*/

// 29-9-2025 shorter function for io_mouse_get. now 4 cycles.

function io_mouse_get()   // 27-11-2024  subroutine, generate code to get clock in F and input data (inverted) in TC
{  // the two input bits come from the parallel input port
	// For mouse, the input port was already read.
	
	ins6(nop, to_t, asl, acc_t, reg_kb_tmp, nop); // bit2 <- clk, bit3 <- data
	ins6(nop, to_dpl, and_tst, acc_t, lit4, nop); // select bit2, to tc. dpl unused.
	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop); // F <- tc, nop
	ins6(nop, to_dpl, and_tst, acc_t, lit8, nop); // select bit3, to tc. dpl unused.
	// this will leave TC set to 1 if the data input was 1
}


function io_mouse_startbit(opc)   // wait until the clock gets low
{
	opcode_page(page_reset, opc, 'io_mouse_startbit', nop, nop); // 
	io_mouse_get();

	//  F = 0 clock low, go to next state        F = 1 clock still high, stay in this state 
	//  but data must be low !! 
	//  Keyboard RX: Move TC to F. If the startbit is not low, we stay in this state.
	if_f_t(in_f(tc_to_f, to_t, ld, acc_t, lit0, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: move TC to F  

    // 11-5-2024 add fillers to get to 0x10 cycles

	ins6(null_m, nop, nop, nop, nop, nop); // 3 extra cycles  28-11-2024
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	
	// go to next state or stay in this state
	if_f_t(in_f(nop, to_t, inc, acc_t, reg_mouse_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, MOUSE_NEXT_DRIVER, page_reset);
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_mouse_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: and store it back	
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

function io_mouse_startbit_end(opc)   // wait until the clock gets high
{
	opcode_page(page_reset, opc, 'io_mouse_startbit_end', nop, nop); // 
	io_mouse_get();
	//       F = 0 clock low, stay in same state        F = 1 clock high, go to next state        
	//  

	ins6(null_m, nop, nop, nop, nop, nop); // 4 extra cycles  28-11-2024
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);

	// go to next state or stay in this state                      
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_mouse_state, nop)); // F=1:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, MOUSE_NEXT_DRIVER, page_reset);
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_mouse_state, nop)); // F=1: and store it back
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}


function io_mouse_databit(opc)   // wait until the clock gets low
{
	opcode_page(page_reset, opc, 'io_mouse_databit', nop, nop); // 
	io_mouse_get();
	// When the clock is low, the data can be read.
	//    F = 0 clock low, go to next state             F = 1 clock still high, stay in this state
	//    
	// Mouse RX   Shift received data bit (TC) into reg-mouse_bitbuf    
	if_f_t(in_f(nop, to_t, rol_tc, acc_t, reg_mouse_bitbuf, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: Shift into bit buffer
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_mouse_bitbuf, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: and store it back

	ins6(null_m, nop, nop, nop, nop, nop); // 2 extra cycles  28-11-2024
	ins6(null_m, nop, nop, nop, nop, nop);

	// go to next state or stay in this state
	if_f_t(in_f(nop, to_t, inc, acc_t, reg_mouse_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, MOUSE_NEXT_DRIVER, page_reset);
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_mouse_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: and store it back	
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

/* TX, per bit:  (as done in io_kb_databit)
   ld T,(txbitbuffer<<1)  
   st (txbitbuffer),t 
   write gp_out1,h/l  // h/l choice comes from DTC
*/

function io_mouse_databit_end(opc)   // wait until the clock gets high
{
	opcode_page(page_reset, opc, 'io_mouse_databit_end', nop, nop); // 
	io_mouse_get();
	//    F = 0 clock low, stay in same state, waiting       F = 1 clock high, go to next state      
	//   

    // 11-5-2024 add fillers to get to 0x10 cycles. Was 9 cycles, so add 7.

	ins6(null_m, nop, nop, nop, nop, nop); // 4 extra cycles  28-11-2024
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop); 
	ins6(null_m, nop, nop, nop, nop, nop);
			
	// go to next state or stay in this state
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_mouse_state, nop));  // F=1:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, MOUSE_NEXT_DRIVER, page_reset);
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_mouse_state, nop)); // F=1: and store it back
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}

function io_mouse_databit_end_last(opc)   // wait until the clock gets high. Special version for end of last databit
{
	opcode_page(page_reset, opc, 'io_mouse_databit_end_last', nop, nop); // 
	io_mouse_get();

	// write Mouse data to the buffer. Also when still waiting for clock, but in that case the bufferpt won't be incremented yet.
	ins6(nop, to_dpl, ld, acc_t, reg_mouse_ptin, nop);
	ins6(nop, to_dph, ld, acc_t, lit1, nop);  // address 0x01pp  (pp = ptin)
	ins6(nop, to_t, ld, acc_t, reg_mouse_bitbuf, nop);
	ins6(nop, to_mem, ld, acc_t, ext, bank0);		 // write to memory in bank 1 !! // 27-11-2024 for Mouse, in bank0

	//    F = 0 clock low, stay in same state, waiting       F = 1 clock high, go to next state      
	//       
	// go to next state or stay in this state                       
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_mouse_state, nop));  // F=1:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, MOUSE_NEXT_DRIVER, page_reset);
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_mouse_state, nop)); // F=1: and store it back
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}


function io_mouse_paritybit(opc)   // wait until the clock gets low
{
	opcode_page(page_reset, opc, 'io_mouse_paritybit', nop, nop); // 
	io_mouse_get();

	//    F = 0 clock low, go next state          F = 1 clock still high, stay in this state

	// output TX. Check if the buffer is empty, result in reg_tx_state

    // 11-5-2024 add fillers to get to 0x10 cycles. Was 9 cycles, so add 7.

	ins6(null_m, nop, nop, nop, nop, nop); // 4 extra cycles  28-11-2024
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop); 
	ins6(null_m, nop, nop, nop, nop, nop);	

	// go to next state or stay in this state
	if_f_t(in_f(nop, to_t, inc, acc_t, reg_mouse_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0:  get incremented state
	ins6(nop, to_t, ld_ir, acc_t, MOUSE_NEXT_DRIVER, page_reset);
	if_f_t(in_f(nop, to_mem, ld, acc_t, reg_mouse_state, nop), in_t(null_m, nop, nop, nop, nop, nop)); // F=0: and store it back	
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}


function io_mouse_paritybit_end(opc)   // wait until the clock gets high
{
	opcode_page(page_reset, opc, 'io_mouse_paritybit_end', nop, nop); // 
	io_mouse_get();
	//    F = 0 clock low, stay in same state, waiting       F = 1 clock high, go to next state (that's the first state, KB_STATE_WAIT)     
	//                                                                                    
    // Mouse RX
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, inc, acc_t, reg_mouse_ptin,nop)); // F=1:  get incremented kb_ptin
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_mouse_ptin,nop)); // F=1: and store it back	

	ins6(null_m, nop, nop, nop, nop, nop); // one extra cycle   28-11-2024

	// 27-11-2024  create literal for MOUSE_STATE_WAIT, 0xd0
	ins6(nop, to_t, asl, acc_t, lit40, nop); // T <- 80  ( 0x50 ). Next line makes it 0xd0.

	// go to next state or stay in this state
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_t, or, acc_t, reg_128, nop)); // F=1: state: MOUSE_STATE_WAIT 
	ins6(nop, to_t, ld_ir, acc_t, MOUSE_NEXT_DRIVER, page_reset);
	if_f_t(in_f(null_m, nop, nop, nop, nop, nop), in_t(nop, to_mem, ld, acc_t, reg_mouse_state, nop)); // F=1: and store it
	no_print_cycles_upd_f_error = 1;
	no_f_is_irq_error = 1; // allow that F is not IRQ
	print_cycles();
}


//**********  sound driver  ***********

//const SOUND_NEXT_DRIVER = reg_isa  // back to user program (reg_isa points to an instruction in the reset page)

// io_wr_sound will take more than 16 cycles !!! (0x29 cycles)

// 1-9-2025 io_wr_sound has two versions:
// opc = sound_state_idle  #95  for PSG. Need this mode also for startup (Keyboard/mouse init)
// opc = sound_state_zx    #9B  for ZX-spectrum / Apple-2

function io_wr_sound(opc)   // wr sound register, clear interrupt flipflop, and jump to video action
{
	opcode_page(page_reset, opc, 'io_wr_sound', nop, nop); // 

	// Normally, writing to the sound register is done here soon after every line interrupt, and
	// it will at the same time clear the interrupt request by toggling the IRQ flipflop.
	// The byte value to write is in T   
	// The WR_SOUND/ is also used to reset the IRQ.
	// A short HIGH pulse on WR_SOUND/ will reset (actually toggle) the IRQ
	// Therefore, the default for WR_SOUND/ is LOW.

     // 29-4-2024  increment the 16-bit video pointer by 1.
 
	ins6(nop, to_t, inc, acc_t, reg_vga_ptl, nop); // T <- reg_vga_ptl + 1
	ins6(nop, to_mem, ld, acc_t, reg_vga_ptl, nop); // store incremented L register
	ins6(nop, to_t, inc_dtc, acc_t, reg_vga_pth, nop); // 
	ins6(nop, to_mem, ld, acc_t, reg_vga_pth, nop); // store incremented H register	
	// Now, the reg_vga_pt will have a value from 0x0700 to 0x090D

	ins6(nop, to_mem, ld, acc_a, reg_kb_tmp, nop); // save A

	if (opc==SOUND_STATE_IDLE)  // PSG sound system
	  {
		// 13-5-2025 new sound system (PSG). This sums 4 different sound channels and moves result to the D/A converter.

		// There are 4 sound buffers, of 1kB each. All in HW bank1.
		// The basic address will start at 1000, counting up until 13FF. Wrap-around by resetting bit3. Other buffers:
		// 0C00      (1000 minus 400)
		// 1000      basic address 1000
		// 1400      (1000 plus 400)
		// 1800-1BFF (1000 plus 800)
		// 1C00-1C10 buffer overflow area
		// Note 700 - 90F is the frame table

		ins6(nop, to_t, asl, acc_t, reg_snd_pth, nop); // 14-5-2025 get mute flag in tc

		ins6(nop, to_t, inc, acc_t, reg_snd_ptl, nop); // T <- reg_snd_ptl + 1
		ins6(dtc_to_f, to_mem, ld, acc_t, reg_snd_ptl, nop); // store incremented L register, mute flag to F
		ins6(nop, to_t, inc_dtc, acc_t, reg_snd_pth, nop); // msb, in reg T
		ins6(nop, to_t, res2, acc_t, lit4, nop);  // do wraparound by resetting bit3. 0524F changes to reset bit2(lit4), buffer 1000

		// 14-5-2025
		if_f_t(in_f(nop, to_mem, ld, acc_t, reg_snd_pth, nop), in_t(nop, to_t, or, acc_t, lit0, nop)); // F0: store msb  F1: while muted, dont change msb

		ins6(nop, to_dpl, ld, acc_t, reg_snd_ptl, nop); // sound pointer to dph/dpl
		ins6(nop, to_dph, add, acc_t, lit0, nop);	

		ins6(nop, to_a, ld, acc_t, ext, bank1); // load from 1400 buffer to A (is now 1000, next lines must change)
		
		ins6(nop, to_dph, sub, acc_t, lit4, nop); // select buffer 0C00
		ins6(nop, to_a, add, acc_a, ext, bank1); // add from 0C00 buffer to A

		ins6(nop, to_dph, add, acc_t, lit4, nop); // select buffer 1400
		ins6(nop, to_a, add, acc_a, ext, bank1); // add from 1000 buffer to A	

		ins6(nop, to_dph, add, acc_t, lit8, nop); // select buffer 1800
		ins6(nop, to_t, add, acc_a, ext, bank1); // add from 1800 buffer to A (no, to T)

		// finally, add 128 to have a zero-level at 1/2 of operating voltage.
		if_f_t(in_f(nop, to_t, add, acc_t, reg_128, nop), in_t(nop, to_t, ld, acc_t, reg_sound, nop)); // F0: add 128  F1: while muted, reg_sound

		// note that reg_sound is used during KB and mouse reset, to write to the output port.
		// The sum of the sound streams is in T now			
	  }
	else // ZX Zpectrum sound system
	  {
		// 16-6-2024  sound output for simple speaker-toggling systems
		// The speaker samples are in bank0 at around 0x0483 and higher (approx 141 of them). 
		// The reg_snd_pt is a pointer to the speaker samples, It will be incremented every 4 lines to
		// do a crude speed conversion.

		ins6(nop, to_t, inc, acc_t, lit1, nop); // T <- 2
		ins6(nop, to_t, add, acc_t, lit1, nop); // T <- T + 1
		ins6(nop, to_t, and, acc_t, reg_vga_ptl, nop);  // reg_vga_ptl AND 0x03
		ins6(nop, to_t, dec_acc, acc_t, lit0, nop); // decrement accumulator T. Will set TC if not zero.
		ins6(tc_to_f, to_t, ld, acc_t, lit0, nop); // F <- TC	
		ins6(nop, to_t, inc, acc_t, reg_snd_pt, nop); // get incremented sound pointer
		if_f_t(in_f(nop, to_mem, ld, acc_t, reg_snd_pt, nop), in_t(nop, to_t, add, acc_t, lit0, nop)); // F=0: and store it F=1 not store
		// have the sound pointer in T now
		// Here we suppose that the frame starts at 0x0300. Then, the sample is at 0x480 + T
		ins6(nop, to_dpl, add, acc_t, reg_128, nop);   // dpl <- T + 0x80
		ins6(nop, to_dph, inc_tc, acc_t, lit4, nop);   // dph <- 4  ( but if TC set, TC <- 5 )
		
		ins6(nop, to_t, ld, acc_t, ext, bank0);    // T <- speaker sample13-11-2024 in bank0 now	
		
		// 16-6-2024 end

		ins6(nop, to_t, xor, acc_t, lit0, nop); // 1-9-2025   extra cycles to get to 16
		ins6(nop, to_t, xor, acc_t, lit0, nop); 
		ins6(nop, to_t, xor, acc_t, lit0, nop); 
		ins6(nop, to_t, xor, acc_t, lit0, nop); 
		ins6(nop, to_t, xor, acc_t, lit0, nop); 
		ins6(nop, to_t, xor, acc_t, lit0, nop);		
	  }

	// 30-6-2025. frame table moved from 0x0300 to 0x0700. Two extra cycle used.
	// But the table with line addresses still starts at 300. Subtract 0x0400
	ins6(nop, h_to_sw_wr_sound_n, ld, acc_t, lit0, nop);  // wr_sound/ HIGH ( low-to-high, data gets written here )

	ins6(tc_to_f, to_dpl, ld, acc_t, reg_vga_ptl, nop);  // load vga pointer lsb, 15-8 tc_to_f

	ins6(nop, l_to_sw_wr_sound_n, ld, acc_t, lit0, nop);  // wr_sound/ LOW	 15-8 moved up to here

	ins6(l_to_f, to_dph, ld, acc_t, reg_vga_pth, nop); // 31-8-2025 clear the F flag

	ins6(nop, to_t, ld, acc_t, reg_vga_pth, nop); // 1-9-2025 load PTH for subtracting 0x04 from it	28-9-2025 moved to v_hires

	// 12-5-2024 go to video function
	ins6(bank1, to_t, ld_ir, acc_t, ext, page_reset); // jp to the video instruction that is found in bank1
	ins6(nop, to_a, ld, acc_a, reg_kb_tmp, nop); // 28-9-2025 here (restore A)

	no_print_cycles_upd_f_error = 1;
	print_cycles();
}


function make_v_pix_hires(opcode,banknr)
{
	opcode_page(page_hires, opcode, 'v_pix_hres', nop, nop); // 16-11-2024 use page_hires

	// this function is called twice, once for bank0 (upper screen half) and once for bank2 (lower screen half)

	// 16-11-2024  handle 320 bytes. Each byte has two pixels of 16 colors each.
	// At entry, F flag must be 0.
	// 13-6-2025 at entry, A must be 0 (used at end)
    i =0;
	while (i<256)
	  { 
		// 15-9-2025 changed ld to ld_640, to select 640-pixel mode on pcb ISA2532
		// 13-6-2025
		if (i == 250)
         { ins6(h_to_f, to_t, ld_640, acc_t, pc_pp, banknr); } // around byte 250, set F		 
		else
		/* 
		if (i == 64) // if F is set, end of video line.
         { if_f_t(in_f(nop, to_t, ld, acc_t, pc_pp, banknr),in_t(nop, to_t , ld, acc_t, lit0, nop) );  } // F=1: clr T		 
		else
		*/
		// after 0914C, 66,67 become 67,68
		if (i == 67) // if F is set, end of video line.
         { if_f_t(in_f(nop, to_t, ld_640, acc_t, pc_pp, banknr),in_t(h_to_sw_vdu_n, to_a , ld, acc_a, lit0, nop) ); } // F=1: de-activate video
		else	
		if (i == 68) // if F is set, end of video line.
         { if_f_t(in_f(nop, to_t, ld_640, acc_t, pc_pp, banknr),in_t(nop, to_t , ld_ir, acc_a, reg_kb_state, page_reset) ); } // F=1: wait for next interrupt
		else			
			
		ins6(nop, to_t, ld_640, acc_t, pc_pp, banknr);  // two pixels from bank0
	  i++;
	  }	
    print_cycles();	
	}


function make_v_pix320(opcode,banknr)
{
	opcode_page(page_reset, opcode, 'v_pix320', nop, nop); // 20-2-2025  use page_reset (thats 320 pix resolution)

	// 20-2-2025  handle 320 bytes. Each byte has one pixels of 64 colors.
	// Normally, reading occurs from the banknr.
	// But when bit7=1, the F flag will be set, and reading occurs from the spritebank.
	// In the spritebank, bit7 is always 1. As soon as it is a 0, F will be reset, and control goes back to the normal bank again.
	// During the jump, there is no reading of a pixel, and the color in ACC will be shown, that was put there at the start of the line.
	// At entry, F flag must be 0.
	banknr=bank0;
	spritebank=bank2;
    i =0;
	while (i<256)
	  { if (i != 254)  //  need: T <- (pc++), upd_n, n_to_f, banknr. Use the acc_t position, that is 0, to put the upd_n.
         { if_f_t(in_f(n_to_f, to_t, ld, upd_n, pc_pp, banknr),in_t(n_to_f, to_t, ld, upd_n, pc_pp, spritebank) );  } // F=0: normal  F=1: sprite		 
		else
        // at position 254, place a jp to the next section, and display A. Here, the to_t files is used to put upd_n.
         { if_f_t(in_f(n_to_f,upd_n, ld_ir, acc_a, reg_vga_lsb, banknr),in_t(n_to_f,upd_n, ld_ir, acc_a, reg_vga_lsb, spritebank) ); } 	
	  i++;
	  }	
    print_cycles();	
	}

function make_v_p320b(opcode,banknr)  	// 20-2-2025  handle the remaining 64 bytes, to complete the 320 bytes
{
	opcode_page(page_reset, opcode, 'v_p320b', nop, nop); // 20-2-2025  use page_reset (thats 320 pix resolution)

	banknr=bank0;
	spritebank=bank2;
    i =0;
	while (i<64)
	  { //  need: T <- (pc++), upd_n, n_to_f, banknr. Use the acc_t position, that is 0, to put the upd_n.
        if_f_t(in_f(n_to_f, to_t, ld, upd_n, pc_pp, banknr),in_t(n_to_f, to_t, ld, upd_n, pc_pp, spritebank) );  // F=0: normal  F=1: sprite		 		
	  i++;
	  }	
	// end of line code, copied from Hires  
    if_f_t(in_f(nop, to_t, ld, acc_t, pc_pp, banknr),in_t(h_to_sw_vdu_n, to_t , ld, acc_t, lit0, nop) ); // F=1: de-activate video
    if_f_t(in_f(nop, to_t, ld, acc_t, pc_pp, banknr),in_t(irq_to_f, to_t , ld_ir, acc_t, lit40, page_reset) ); // F=1: wait for next interrupt
    print_cycles();	
	}	

// function do_speaker   31-8-2025

// called from v_blank, v_wait

function do_speaker()
{
	ins6(nop, to_dph, sub, acc_t, lit4, nop); // 30-6-2025 subtract 0x04, result to DPH  (31-8-2025 here)

	// 15-9-2025 new section to prevent irritating high freq tone
	ins6(nop,to_t,asl,acc_t,reg_speaker,nop);  // T <- asl(reg_speaker) // find polarity, to TC
	ins6(tc_to_f, to_t, ld, acc_t, reg_speaker, nop); // T <- speaker
	ins6(nop,to_mem,ld,acc_t,ext,bank0); // save in bank0. after this, can use dpl.

	// F:   bit7=0 incr until 0x80                   T:  bit7=1 NOP
	if_f_t(in_f(nop, to_t, ld, acc_t, reg_speaker, nop), in_t(nop, to_t, dec, acc_t, reg_speaker, nop)); // F: nop T  T: dec
	if_f_t(in_f(nop, to_dpl, xor, acc_t, lit0, nop), in_t(nop, to_dpl, dec_acc, acc_t, lit0, nop)); // F: nop T  T: dec (result in dpl)
  
	ins6(nop,to_t,asl,acc_t,dpl,nop);   // find polarity after inc, to TC	
	
	if_f_t(in_f(nop, to_t, xor, acc_t, lit0, nop), in_t(tc_to_f, to_t, xor, acc_t, lit0, nop)); //  F: nop  T: nop, F<-tc

	// F:   bit7=0 NOP               T:  bit7=1  decr until 0x80 (when it was >80, or became >80 after inc)
	if_f_t(in_f(nop, to_t, inc , acc_t,  dpl, nop), in_t(nop, to_t, ld    , acc_t,  dpl, nop)); // F: inc  T: nop
	if_f_t(in_f(nop, to_t, inc_acc, acc_t, lit0, nop), in_t(nop, to_t, xor, acc_t, lit0, nop)); // F: inc  T: nop
	// at exit, speaker value must be in T
}

// function video_init   12-5-2024

function video_init()
  { // Here follow the video instructions. Every instruction will be entered with flag F=0.
	
	//******  V_PREPARE prepare for display area. Save application registers PCH/PCL, ACC and some flags, and wait for next interrupt
	opcode_page(page_reset, 0x24, 'v_prepare', nop, nop);

	// new 27-3-2025
	ins6(nop, to_mem, ld, acc_a, reg_vga_acc, nop); // save Accumulator (in current EXX)

	ins6(nop, to_t, asl, acc_t, reg_ch_sel, nop); // bit7 of PSG-channel selection to tc

	ins6(tc_to_f, to_t, ld, acc_t, reg_sel, nop);  // get current register EXX selection, tc_to_f

	if_f_t(in_f(nop, h_to_sw_exx , ld, acc_t, lit0, nop),  //  15-8-2025 normal (bit7=0), set sw_exx = high 
	       in_t(nop, l_to_sw_exx , ld, acc_t, lit0, nop));  // 15-8-2025 sleep mode, set sw_exx = low

	ins6(nop, to_mem, ld, acc_t, reg_exx, nop);  // save register EXX selection to reg_exx	

    // 13-5-2024 save some flags. copied from PHP/PLP, can be simplified 
	ins6(nop, to_dpl, rol, acc_t, reg_v, nop);  // get V bits, shift left -VV---VC  and put cy in bit0  16-4
	ins6(n_to_f, to_t, ld, acc_t, reg_128, nop);      // bit7 in t, n flag to F

	// 29-3-2025B  process N flag, but put result in T
	// F: reset bit 7                        T: set bit 7
	if_f_t(in_f(nop, to_t, res, acc_t, dpl, nop), in_t(nop, to_t, or, acc_t, dpl, nop)); // reset or set bit7

	// final result NVV---VC  (no Z flag)
	// 29-3-2025B  end

	// 30-9-2025 the next two lines seem to do nothing...
	ins6(nop,to_a,asl,acc_a,lit32,nop); // value 2 * 0x20 --> 0x40  (make literal is too long)
	ins6(nop,to_dpl,add,acc_a,lit8,nop);    // + 8  -> 0x48 is rtc_tick

	// 27-9-2025 rtc_tick now at 0x23 
	ins6(nop,to_a,inc,acc_a,lit32,nop); // value 0x21   (make literal is too long)
	ins6(nop,to_dpl,add_1,acc_a,lit1,nop);    // add 2 to get 0x23 () rtc_tick )
    
	ins6(irq_to_f, to_t, ld_ir, acc_t, dpl, page_rtc); // 9-8-2025 jump to rtc_tick
	// 25-3-2025  ins6(null_m, nop, nop, nop, nop, nop);	
	ins6(nop, to_mem, ld, acc_t, reg_vga_flags, nop); // 25-3-2025 moved to here

    print_cycles();

    //******  V_END end of display area. Restore application registers and flags and go back to user application
	opcode_page(page_reset, 0x25, 'v_end', nop, nop);

	ins6(nop, to_pch, ld, acc_t, reg_tl, nop);  // restore pcl
	ins6(nop, to_pch, ld, acc_t, reg_th, nop); 	// restore pch

	// 13-5-2024 restore flags. copied from PLP. can be simpler
	// 5-7-2023 storage format:  NVV--ZVC  (Z is inverted)
	// 4-12-2024 writing the N flag interferes with SPI operation, it causes an extra clock pulse.
	// But the N flag is never changed in the HW interrupt. So we don't have to 'restore' it !
	ins6(nop, to_t, ld, acc_t, reg_vga_flags, nop);    // get flags, update N flag 4-12-2024 don't restore N flag	

 	ins6(irq_to_f, to_dpl, ld, acc_t, reg_vga_flags, nop);    // get flags to dpl
	// 24-6-2025  new SHR. The next SHR will not work, but since it's result is not used (no V flag restore), it doesnt matter.
	ins6(nop, to_t, shr, acc_t, dir, upd_c); // do a right shift, obtain C and have V in position	
	// 30-11-2024 note that V is not restored !!!!	But it doesn't need to , it hasnt changed.	   
	// probably also reg_z need no restore.
    // end flag restore

	// 30-12-2024 yes we need to set bankswitch back, the ZX-spectrum pixel writer writes rubbish to bank register
	ins6(nop, to_bnk, ld, acc_a, reg_bank_dp, nop); // Write BANK register. also writes dph. use acc_a. 30-12-2024

	// 2-10-2024 set frame interrupt request bit in irq_register, this will trigger a "RST #38" interrupt.
	ins6(nop,to_t,inc,acc_t,lit0, nop); // T <- 1
  	ins6(nop,to_t,or,acc_t,reg_irq, nop);   // T <- 1 OR reg_irq
  	ins6(nop,to_mem,ld,acc_t,reg_irq, nop);

	// new 27-3-2025 restore register bank
	ins6(nop, to_t, compl, acc_t, reg_exx, nop);  // get saved register EXX selection. complement it.

	// Note that r0 goes through a HW inverter just before the condition selector.
	ins6(nop, r0_to_sw_exx, ld, acc_t, lit0, nop);  // r0 must be on result bus in prev cycle. Restore correct EXX bank.
	// end 27-3-2025	

    ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // 6-10-2024 l-to_f
	ins6(nop, to_a, ld, acc_t, reg_vga_acc, nop); // 30-11-2024 restore accumulator
	
    print_cycles();
    
	//****** V_BLANK blank video line. This does nothing. Just returns to the application.
	// 17-6-2024 but it checks if a write to the speaker was done during the last line, and processes that signal.
	opcode_page(page_reset, 0x26, 'v_blank', nop, nop);

 	do_speaker();  // 31-8-2025. do_speaker needs T and DPH from wr_sound

	// 2-10-2024 implement interrupt mode 1
	ins6(nop,to_dpl,inc,acc_t,reg_irq,nop); // 2-10-2024 if reg_irq=FF, an RST #38 interrupt must occur

    ins6(tc_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // 2-10-2024 do tc_to_f instead of irq_to_f, get irq_zero condition in F
	
	ins6(nop,to_mem,ld,acc_t,reg_speaker,nop);  // store the re-calculated speaker sample. 6-10 remove irq_to_f
    print_cycles();		

    //****** V_WAIT wait for next interrupt, so that the response to that interrupt has predictable timing
	opcode_page(page_reset, 0x27, 'v_wait', nop, nop);

	do_speaker();  // 31-8-2025

	// 9-8-2024  // not allowed to use ACC.  So, first store spkr value
	ins6(irq_to_f,to_mem,ld,acc_t,reg_speaker,nop);  // store the re-calculated speaker sample in reg_speaker	

	make_literal(to_t,rtc_tick2); 
	ins6(nop,to_dpl,add,acc_t,lit0,nop);
    ins6(irq_to_f, to_t, ld_ir, acc_t, dpl, page_rtc); // 9-8-2025 jump to rtc_tick2	
	ins6(null_m, nop, nop, nop, nop, nop);
    print_cycles();

    //****** V_IWAIT  actually waits for an interrupt. Flag F must be set before going here.
	opcode_page(page_reset, 0x28, 'v_iwait', nop, nop);  // opcode 0x28,  is 40 decimal.

	//        F: interrupt active                         T: no interrupt, jmp back to 0x28 V_IWAIT
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, reg_kb_state, page_reset), in_t(irq_to_f, to_t, ld_ir, acc_t, lit40, page_reset));
	if_f_t(in_f(nop, to_t, ld_ir, acc_t, reg_kb_state, page_reset), in_t(irq_to_f, to_t, ld_ir, acc_t, lit40, page_reset));

    print_cycles();		

	// opcode 0x29 is kept free for future use

    //****** V_ACT_VSYNC activate vertical sync signal
	opcode_page(page_reset, 0x2A, 'v_act_vsync', nop, nop);

	// just copy speaker from prev sample	
	ins6(nop, to_dph, sub, acc_t, lit4, nop); // subtract 0x04, result to DPH  (31-8-2025 here)
	ins6(nop,to_t,ld,acc_t,reg_speaker,nop); // 31-8-2025  T <- reg_speaker
	ins6(nop,to_mem,ld,acc_t,ext,bank0);  // 31-8-2025  store the speaker sample in bank0		

	ins6(nop, to_dpl , ld, acc_t, reg_sel, nop);  // 27-3-2025 get current EXX to dpl

	// 3-11-2024 removed: ins6(nop, l_to_sw_vsync_n , ld, acc_t, lit0, nop);
	// 3-11-2024 new
	// the four or six video signals come from the operand bus. These signals should be low.
	ins6(nop, to_t , ld, acc_t, lit0, nop); // 15-11-2024 set T = 0

	ins6(nop, l_to_sw_exx , ld, acc_t, lit0, nop); // exx low	  27-3-2025
	ins6(nop, l_to_sw_vdu_n , ld, acc_t, lit0, nop);	 // vdu/ low  (this will clock the EXX signal into the VSYNC Flipflop in U51)  VSYNC is now active
	ins6(null_m, nop, nop, nop, nop, nop);               // nop
	ins6(nop, h_to_sw_vdu_n , ld, acc_t, lit0, nop);	 // vdu/ high
	// 3-11-2024 end

	// new 27-3-2025 restore register bank
	ins6(nop, to_t, compl, acc_t, dpl, nop);  // get saved register EXX selection. complement it.
	// Note that r0 goes through a HW inverter just before the condition selector.
	ins6(nop, r0_to_sw_exx, ld, acc_t, lit0, nop);  // r0 must be on result bus in prev cycle. Restore correct EXX bank.
	// end 27-3-2025	

	// 2-10-2024 clr F
    ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset);
	//ins6(nop, h_to_sw_spi_cs2_n , ld, acc_t, lit0, nop); // spi_cs2/ high  14-12-2024 in delay   27-3-2025A removed
	ins6(null_m, nop, nop, nop, nop, nop);  // 27-3-2025A re-inserted
	
    print_cycles();	


    //****** V_DEACT_VSYNC de-activate vertical sync signal
	opcode_page(page_reset, 0x2B, 'v_deact_vsync', nop, nop);

	// 14-12-2024 first do the speaker, then the sync.

	// just copy speaker from prev sample
	ins6(nop, to_dph, sub, acc_t, lit4, nop); // subtract 0x04, result to DPH  (31-8-2025 here)
	ins6(nop,to_t,ld,acc_t,reg_speaker,nop); // 31-8-2025  T <- reg_speaker
	ins6(nop,to_mem,ld,acc_t,ext,bank0);  // 31-8-2025  store the speaker sample in bank0		

	ins6(nop, to_dpl , ld, acc_t, reg_sel, nop);  // 27-3-2025 get current EXX to dpl

	// 3-11-2024 removed: ins6(nop, h_to_sw_vsync_n , ld, acc_t, lit0, nop);
	// 3-11-2024 new
	// the four or six video signals come from the operand bus. These signals should be low.

	ins6(nop, to_t , ld, acc_t, lit0, nop); // 15-11-2024 set T = 0	

	ins6(nop, h_to_sw_exx , ld, acc_t, lit0, nop); // exx high  27-3-2025	
	ins6(nop, l_to_sw_vdu_n , ld, acc_t, lit0, nop);	 // vdu/ low (this will clock the EXX signal into the VSYNC Flipflop in U51)
	ins6(null_m, nop, nop, nop, nop, nop);               // nop
	// 3-11-2024 end	

	ins6(nop, h_to_sw_vdu_n , ld, acc_t, lit0, nop); //  vdu/ high
	
	// new 27-3-2025 restore register bank	
	ins6(nop, to_t, compl, acc_t, dpl, nop);  // get saved register EXX selection. complement it.
	// Note that r0 goes through a HW inverter just before the condition selector.
	ins6(nop, r0_to_sw_exx, ld, acc_t, lit0, nop);  // r0 must be on result bus in prev cycle. Restore correct EXX bank.
	// end 27-3-2025		

	// 2-10-2024 clr F
    ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset);
	ins6(null_m, nop, nop, nop, nop, nop);  // 25-3-2025  delay

    print_cycles();	


    //****** V_REPEAT repeat the video frame sequence
	opcode_page(page_reset, 0x2C, 'v_repeat', nop, nop);
    // reset the pointer to the VGA line to the VGA_BASE (that can be set to any 0xXX00 value in bank 1 )
	ins6(nop, to_t, dec, acc_t, lit0, nop);  // 0xFF to T
	ins6(nop, to_mem, ld, acc_t, reg_vga_ptl, nop);	 // reg_vga_ptl <- T
	ins6(nop, to_t, dec, acc_t, reg_vga_base, nop);  // T <- reg_vga_base -1	
	ins6(nop, to_mem, ld, acc_t, reg_vga_pth, nop);	 // reg_vga_pth <- T

    ins6(nop,to_t,ld,acc_t,lit4, nop);
 
	ins6(nop, to_mem, ld, acc_t, reg_snd_pt, nop); // 16-6-2024 reset sound pointer 

 	// 2-10-2024 clr F
    ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset);  // back to application
	ins6(null_m, nop, nop, nop, nop, nop); // 31-8-2025 no speaker sample at the end !
    print_cycles();	


    //****** V_HIRES  prepare for displaying one line of hi-res video, 640 pixels
	opcode_page(page_reset, 0x2D, 'v_hires', nop, nop);

	ins6(nop, to_dph, sub, acc_t, lit4, nop); // 30-6-2025 subtract 0x04, result to DPH  (31-8-2025 here)

	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);		
	ins6(null_m, nop, nop, nop, nop, nop); // 1-9-2025  now 3 cycles  13-9-2025 now 2 cycles ?
	ins6(nop, to_t, xor, acc_t, lit0, nop); // 28-9-2025 extra nop, (removed instr from wr_sound)
	// 29-9-2025, io_kb_get and io_mouse_get are now each 2 cycles shorter. so 4 extra cycles here:
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);	
 
	// 16-11-2024 get the address from the table. must be shifted left, upper bit is the page.
	ins6(nop, to_t, asl, acc_t, ext, bank0);
	ins6(nop, to_a, rol_tc, acc_t, ext, bank2); // gives page nr in tc
    // now lsb is in T, msb in A

    // place in vga_msb/lsb and in pch/pcl 

	ins6(tc_to_f, to_mem, ld, acc_t, reg_vga_lsb, nop); // store lsb of video line address // 16-11-2024 add tc_to_f
	ins6(nop, to_mem, ld, acc_a, reg_vga_msb, nop); // store msb of video line address	

	ins6(nop, to_pch, ld, acc_t, reg_vga_lsb, nop); // lsb of video line address
	ins6(nop, to_pch, ld, acc_t, reg_vga_msb, nop); // msb of video line address	

	// 25-11-2024 new address for pixel functions
    // Start with 0x80. Subtract 0x20 or 0x10
	ins6(nop, to_t, ld, acc_t, reg_128, nop); // T <- 0x80
	// F=0  create opcode 0x60               F=1  create opcode 0x70
	if_f_t(in_f(nop, to_dpl, sub, acc_t, lit32, nop), in_t(nop, to_t,   sub, acc_t, lit8, nop));  // F0: sub 0x20  F1: sub 0x08
	if_f_t(in_f(nop, to_t, ld, acc_t, lit0, nop),     in_t(nop, to_dpl, sub, acc_t, lit8, nop));  // F0: nop   F1: dpl<- T sub 0x08

	ins6(nop,to_a,ld,acc_a,lit0,nop); // 13-6-2025 set A to 0

    ins6(l_to_f, to_t, ld_ir, acc_t, dpl, page_hires);  // go to V_PIX_HRES display pixels, set F = 0. 16-11-2024 use page_hires
	ins6(nop, l_to_sw_vdu_n , ld, acc_t, lit0, nop);  // activate VDU output
    print_cycles();	


    //****** V_GRAPHIC320  prepare for displaying one line of graphic video, 320 pixels.  New 6-6-2024

	// 16-11-2024  not used

	// 20-2-2025  start testing and using this mode. Includes sprite display.

	opcode_page(page_reset, 0x34, 'v_graphic320', nop, nop);

    // have a delay, (2 cycles).  Total 20 cycles here.
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);	  
	
	// here 8 cycles follow. Total this will be 48 cycles, so the above delay must be 40

    // normal graphic video lines have the line address in (bank4, bank5)
	// the pointer to the video line table is still in DPH/DPL

	// TODO probably have to subtract 4 from T	result to dpl	

	ins6(nop, to_t, asl, acc_t, ext, bank0);
	ins6(nop, to_a, rol_tc, acc_t, ext, bank2); // gives page nr in cy	.  Shifted right. copied from Hires.

    // now lsb in T, msb in A
    // place in vga_msb/lsb and in pch/pcl 

	// 29-9-2025, io_kb_get and io_mouse_get are now each 2 cycles shorter. so 4 extra cycles here:
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);	


	ins6(l_to_f, to_mem, ld, acc_t, reg_vga_lsb, nop); // store lsb of video line address // 20-2-2025 clear F (no sprite)
	ins6(nop, to_mem, ld, acc_a, reg_vga_msb, nop); // store msb of video line address	

    // copy to dph/dpl  for getting the char at position 254 in A. Will come later. reserve 5 cycles for this.

    ins6(null_m, to_a, ld, acc_a, lit40, nop);  // just some color
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);

	ins6(nop, to_pch, ld, acc_t, reg_vga_lsb, nop); // lsb of video line address
	ins6(nop, to_pch, ld, acc_t, reg_vga_msb, nop); // msb of video line address		

	// Note that the data of each line must be repeated, to get two identical lines, simulating 200 lines on a 400 line screen.

	// this is the 320 x 200 pixel mode. Each pixel is a byte, so 64000 bytes needed ( FA00 hex ). These must be in bank 2 at 0x0600 - 0xFFFF

    // 20-2-2025 There will be a JP to the last ~80 bytes of the line at 0xE8. prepare the address in reg_vga_lsb.
	// Do: (256) +8 -32 --> 232 (0xE8)
	ins6(nop, to_t, ld, acc_t, lit8, nop); // T <- 8
	ins6(nop, to_t, sub, acc_t, lit32, nop); // subtract 0x20. Now have 0xE8
	ins6(nop, to_mem, ld, acc_t, reg_vga_lsb, nop); // store the jp address

    // have to put 0xF0 in DPL, for jumping to V_PIX_320.  how ? Start with 00. Subtract 0x08 two times

	ins6(nop, to_t, ld, acc_t, lit0, nop); // T <- 0	
	ins6(nop, to_t, sub, acc_t, lit8, nop); // subtract 0x08	
	ins6(nop, to_dpl, sub, acc_t, lit8, nop); // subtract 0x08

	ins6(nop, to_t, ld, acc_t, pc_pp, bank0); // get the pixel data from bank 0   Do the very first pixel here.

    ins6(irq_to_f, to_t, ld_ir, acc_t, dpl, page_reset);  // go to V_PIX320 display pixels
	ins6(nop, l_to_sw_vdu_n , ld, acc_t, lit0, nop);  // activate VDU output
    print_cycles();	


    //****** V_SPECTRUM  prepare for displaying one line of ZX Spectrum graphic video, 256 x 192 pixels  New 6-6-2024
	opcode_page(page_reset, 0x0D, 'v_spectrum', nop, nop);

	// 31-8-2025 delay section, use A as counter (T must not be changed)
	/* 15-9-2025 change delay. must be approx 11 pixels less. was 9*5. Now 6*6 
	if_f_t(in_f(nop, to_a, ld, acc_t,lit8, nop),in_t(nop, to_a , xor, acc_a, lit0, nop) ); // F: init delay cnt   T: nop (A <- A xor 0)
	*/
	if_f_t(in_f(nop, to_a, inc, acc_t,lit4, nop),in_t(nop, to_a , xor, acc_a, lit0, nop) ); // 15-9-2025 F: init delay cnt with 5  T: nop (A <- A xor 0)
	if_f_t(in_f(nop, to_a, add, acc_a,lit0, nop),in_t(nop, to_a , xor, acc_a, lit0, nop) ); // 15-9-2025 nop, to get 6 cycles per loop

    ins6(nop, to_a, sub, acc_a,lit1,nop);  // dec repeat counter. Will set TC when A != 0. (before decrementing)
	ins6(tc_to_f, to_a , xor, acc_a, lit0, nop);   // F <- TC and nop ( A <- A xor 0 )
	// note that the start addr of v_spectrum is still in dph/dpl (ext). If F=1, jump back to start, v_spectrum
	if_f_t(in_f(nop, to_a, ld, acc_t,lit0, nop),in_t(bank1, to_a , ld_ir, acc_t, ext, page_reset) ); // F: nop   T: go to v_spectrum
	ins6(nop, to_a , xor, acc_a, lit0, nop); // nop	(delay slot)		
	// end of delay section

	ins6(nop, to_dph, sub, acc_t, lit4, nop); // 30-6-2025 subtract 0x04, result to DPH (31-8-2025 here)

	// 6-7-2024 end of delay 

	ins6(nop, to_t, xor, acc_t, lit0, nop); // 28-9-2025 exta nop, removed instr from wr_sound	

	// 29-9-2025, io_kb_get and io_mouse_get are now each 2 cycles shorter. so 4 extra cycles here:
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);
	ins6(null_m, nop, nop, nop, nop, nop);		

    // normal graphic video lines have the line address in (bank4, bank5)
	// the pointer to the video line table is still in DPH/DPL
    ins6(nop, to_pch, ld, acc_t, ext, bank0);  // 13-11-2024 get lsb of graphic line
    ins6(nop, to_pch, ld, acc_t, ext, bank2);  // 13-11-2024 get msb of graphic line	

    // the MSB of the color-attribute data must be in reg_vga_msb. Calculate it from MSB of bitmap data ?

	// $40xx  -> color at $58xx  first third
	// $41xx (next char row, same color)
	//
	// $48xx  -> color at $59xx  2nd third
	//
	// $50xx  -> color at $5Axx
    // seems difficult to calculate. bitmap addr 010t trrr lllxxxxx  t=thirds(0-2), r=row0-7, l=line0-7, x = x0-31
	// For the bitmap, we can simply store ttrrrlll (8 bits), and shift it left 5 times. (10 cycles shifting...)
	// For attribs, store:                 110ttlll  and shift left 5 times...  again 10 cycles. no good. 
	// But note that there are only 3 values for the attrib. msb.
	// Easiest, and also most flexible, is to put that attrib-msb in its own table. But that bites into the next bank, bank 6.
	// Just set reg_vga_msb to $57 and increment it, every time that the LSB is zero. Hmm but it will be incremented twice since
	// each line displays two times...
	// so have the bitmap start addr divided by two, with a flag in the upper bit
	// Note that the data of each line must be repeated, to get two identical lines, simulating 192 lines on a 384 line screen.
	// So better use soms space in bank6. Anyway, nothing else runs if Speccy is busy.

    ins6(nop, to_t, ld, acc_t, ext, bank1);  // get msb of color attributes	

	ins6(nop, to_mem, ld, acc_t, reg_vga_msb, nop); // store msb of color attr address	
   
    ins6(nop, to_t, ld, acc_t, lit8, nop);  // 13-11-2024 get value 8. This also clears TC (DTC) as used in V_PIX_SPECTRUM.	
	ins6(nop, to_mem, ld, acc_t, reg_vga_lsb, nop); // store at reg_vga_lsb, msb of color translation table

    // 6-8-2024 set colors for the first character

	ins6(nop, to_t, ld, acc_t, lit0, nop); // ld black as border color into T, 
	
	ins6(nop, to_dpl, ld, acc_t, pcl, nop); // f: dpl<-pcl 
	ins6(nop, to_dph, ld, acc_t, reg_vga_msb, nop);   // dph <- reg_vga_msb ; msb of attr byte
	ins6(nop, to_dpl, ld, acc_t, ext, bank3);  // dpl <- (dph/dpl)   get color attr   // 29-11-2024 added bank3
	ins6(dtc_to_f, to_dph, ld, acc_t, reg_vga_lsb, nop); // dph <- reg ; msb of color translation table. Will contain value 2. F <- dtc	
	// dph/dpl now point to the color tables (FG table, BG table) of the first character.
    // end set colors

	// 6-7-2024 slightly different start of scanline. Have both A and T cleared now (black).
	ins6(nop, to_a, ld, acc_t, lit0, nop); // ld black as border color also into A, since first pixel may come from DPH (80 col system)
    // 30-11-2024 
	ins6(l_to_f, to_t, ld_ir, page_zx_video, pc_pp, bank3);  // go to page_zx_video to display pixels 30-11-2024 use bank3	
	ins6(nop, l_to_sw_vdu_n , ld, acc_t, lit0, nop);  // activate VDU output

    print_cycles();	


    //****** V_PIX_SPECTRUM  display one line of zx spectrum video, 256 pixels per line
	//
	//
    i =0;
	while (i<256)  // one sequence of 8 cycles, for every of the 256 possible bitmap bytes
	  { opcode_page(page_zx_video, i , 'v_pix_spectrum', nop, nop);
		
		// For each pixel, check if the color will come from ACC_T or ACC_A
	
		// 5-7-2024 new. Align the pixels exactly with the colors.
		// The last displayed pixel is pixel0. But that is displayed at the NEXT char, where that pixel is no longer
		// available. Trick: when pixel0 is 1, we swap FG and BG, and invert all pixels. Now, pixel0 will always be 0.

        var pos;
		var neg;
		//So, if pixel0 = 0 (bg), the bg goes into t, otherwise, fg into t. (fg bank4, bg bank5)  --> this sets to_fg and to_bg
		//If pixel7=0 (bg), bg is loaded first,. otherwise, fg is loaded first.

		if (i & 0x01) 
		     { pos = acc_t; neg = acc_a; var to_bg= to_a; var to_fg=to_t; }
		else { pos = acc_a; neg = acc_t; var to_bg= to_t; var to_fg=to_a; }  // this is actually the normal case. 1 = FG = acc_a = pos

		if (i & 0x80) pixel7 = pos; else pixel7 = neg;
		if (i & 0x40) pixel6 = pos; else pixel6 = neg;
		if (i & 0x20) pixel5 = pos; else pixel5 = neg;
		if (i & 0x10) pixel4 = pos; else pixel4 = neg;	
		if (i & 0x08) pixel3 = pos; else pixel3 = neg;
		if (i & 0x04) pixel2 = pos; else pixel2 = neg;
		if (i & 0x02) pixel1 = pos; else pixel1 = neg;
		if (i & 0x01) pixel0 = pos; else pixel0 = neg;		

		if (i & 0x80)					
		     { var first_bank=bank0; var sec_bank = bank2; var first_to = to_fg; var sec_to = to_bg;   }  
		else { var first_bank=bank2; var sec_bank = bank0; var first_to = to_bg; var sec_to = to_fg;   }  
			
		//   F = 0   normal character               F = 1  end of character sequence

		// So it starts with pixel0 (of prev char), then continues with 7, 6, 5 etc

        // the first instruction does not specify a pixel. The color always comes from acc_t. The pixel belongs to the prev char.

		// 6-7-2024
   		if_f_t(in_f(first_bank, first_to, ld, acc_t, ext, nop),in_t(nop, to_t, ld, acc_t, lit0,nop) ); // ld FG color into A, T: A <- 0  
		if_f_t(in_f(sec_bank, sec_to, ld, acc_t, ext, pixel7),in_t(nop, to_t, ld_ir, acc_t, lit40, page_reset) ); // ld BG color into T, T: jp to IWAIT 		
		if_f_t(in_f(bank1, to_dph, asl, acc_t,pc_ind, pixel6),in_t(nop, h_to_sw_vdu_n , ld, acc_t, lit0, nop) ); // F: eol flag to TC, bit7=1   T: de-activate VDU output

		// next line added upd_n, see notes line 13614
		ins6(nop, to_dpl, ld, nop, pcl, pixel5 ); //  dpl<-pcl. bit6,7 might be set. 4-12-2024 upd_n removed		
		
		ins6(dtc_to_f, to_dph, ld, nop, reg_vga_msb, pixel4);   // dph <- reg_vga_msb ; msb of attr byte. 4-12-2024  upd_n removed now. Interferes with SPI.

		// the following can set bit6 (LL6) active, giving a stripe in the last instruction.
		// but we might load the value through the UPPER logic unit... so ALU control must be 01010
		// So we need an instruction LDU (load through upper logic unit)
		// Strange is, LDU doesnt work. No sync on VGA screen.
		// perhaps the end-of-line flag is clobbered ?? That must be it.
		// Do the dtc_to_f at another position
		ins6(nop, to_dpl, ldu, pixel3, ext, bank3);  // dpl <- (dph/dpl)   get color attr. bit6,7 might be set.	29-11-2024 added bank3	

		// 29-11-2024 ins6(page_zx_video, to_t, ld_ir, acc_t, pc_pp, pixel2);  // prepare jump to next character
		ins6(page_zx_video, to_t, ld_ir, pixel2, pc_pp, bank3);  // prepare jump to next character 29-11-2024 added bank3		
        // for upd_n instead of acc_t, see notes at 12885. acc_t could be removed since it is all-zero.
		// 30-6-2024 upd_n also in T-part.

		ins6(nop, to_dph, ld, nop, reg_vga_lsb, pixel1); // dph <- reg ; msb of color translation table. Will contain value 2. F <- dtc. 4-12-2024 upd_n removed	

		// 30-11-2024 Note that this function often writes DPH with ACC_A. That means that also the BNK 
		// register is written ! So the BNK register must be restored directly after writing to the screen.
	    print_cycles();	
	  i++;
	  }

    //****** V_PIX_HRES  display one line of hi-res video, 640 pixels
		 
	 make_v_pix_hires(0x60,bank0); // 25-11-2024
	 make_v_pix_hires(0x70,bank2); // 25-11-2024

     make_v_pix320(0xF0,bank0); // 20-5-2025 // banknr is re-defined in the function.
     make_v_p320b (0xE8,bank0); // 20-5-2025	 
  
  }


// 8-8-2025 RTC  Real time clock

// better have rtc on private page until it works .....  page 24 ??  page_rtc.

function testlimit(startvalue)  // startvalue is lit0 or lit1
{
	ins6(nop,to_t,xor_tst,acc_t,ext,time_bnk);  //compare counter with loaded literal
	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop); // nop, tc_to_f
	ins6(nop,to_t,inc,acc_t,ext,time_bnk);  // load counter, increment it
	if_f_t(in_f(nop, to_t, ld, acc_t,startvalue, nop),    // false: limit reached, load zero
	       in_t(nop, to_t, ld_ir, acc_t, lit0, page_rtc) ); // 23-9-2025 true:  jp to rtc_exit (#0)		   
	ins6(nop,to_mem,ld,acc_t,ext,time_bnk);   // store the changed counter
}

// Each rtc_tick occurs after 525 lines. 59.52381 Hz  It calls the 60 Hz clock rtc_60s.
// It subtracts 11 (0x000B) from the fraction.

// Shortly after rtc_tick, rtc_tick2 occurs.
// If the fraction is below zero, 1239 is added (1024 + 215) to fraction, and 60Hz clock is called
// for an extra pulse.


function build_rtc()
  {
	opcode_page(page_rtc, rtc_tick, 'rtc_tick', nop, nop); // main entry, every frame start

	// 15-8-2025 PC change moved from v_prepare to here
	ins6(nop, to_t, ld, acc_t, pcl, nop);		// get pcl move it to t
	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // store pcl in reg_tl temporary location)
    ins6(nop, to_pch, ld, acc_t, lit0, nop);   // write to pch to get pch into pcl
	ins6(nop, to_t, ld, acc_t, pcl, nop); // t <- pcl (this is actuall pc-msb)
	ins6(nop, to_mem, ld, acc_t, reg_th, nop); // store pcl in reg_th temporary location)	

	// subtract 11 (0x0B), same as add FFF5
	make_literal(to_t,0xF5);
	ins6(nop,to_dpl,ld,acc_t,lit0,nop);   // time_frac = 0
	ins6(nop,to_dph,inc,acc_t,lit4,nop);   // time_msb = 5	

	ins6(nop,to_t,add,acc_t,ext,time_bnk);  // add fraction lsb to F5
	ins6(nop,to_mem,ld,acc_t,ext,time_bnk);  // store fraction lsb back
	ins6(nop,to_dpl,inc,acc_t,dpl,nop); // select msb

	ins6(nop,to_t,dec_dtc,acc_t,ext,time_bnk);  // add msb to FF by decrementing
	ins6(nop,to_mem,ld,acc_t,ext,time_bnk);  // store fraction msb back

	//make_literal(to_t,0xEA);
	make_literal(to_t,0x1A);	// 15-8-2025	
	ins6(nop,to_dpl,add,acc_t,lit0,nop); // dpl <- T

    // await interrupt
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_rtc); // jump to rtc_60s  1/60th second
	ins6(delay_m,nop,nop,nop,nop,nop);
    print_cycles();	
	//------------------------------
	opcode_page(page_rtc, rtc_tick2, 'rtc_tick2', nop, nop); // secundary entry, somewhere halfway every frame

	ins6(nop,to_dpl,ld,acc_t,lit1,nop);   // time_frac_msb = 1
	ins6(nop,to_dph,inc,acc_t,lit4,nop);   // time_msb = 5	
	ins6(nop,to_t,asl,acc_t,ext,time_bnk); // bit15 of fraction to tc

	ins6(tc_to_f,to_dpl,ld,acc_t,lit0,nop);   // time_frac_lsb = 0, tc_to_f
	if_f_t( in_f(irq_to_f, to_t, ld_ir, acc_t, lit40, page_reset),    // tc=0: jump to V_IWAIT
	        in_t(nop,to_t,xor,acc_t,lit0,nop));     // tc=1: nop

	make_literal(to_t,215  )   // number: 1239 ( 1024 + 215)
	ins6(nop,to_t,add,acc_t,ext,time_bnk);  // add fraction lsb to 215
	ins6(nop,to_mem,ld,acc_t,ext,time_bnk);  // store fraction lsb back

	ins6(nop,to_t,ld,acc_t,lit4,nop); // T <- value 4  ( 4 * 256 = 1024 )
	ins6(nop,to_dpl,inc,acc_t,dpl,nop); // select msb	
	ins6(nop,to_t,add_dtc,acc_t,ext,time_bnk);  // add fraction msb to 4
	ins6(nop,to_mem,ld,acc_t,ext,time_bnk);  // store fraction msb back

	//make_literal(to_t,0xEA);
	make_literal(to_t,0x1A);	// 15-8-2025
	ins6(nop,to_dpl,add,acc_t,lit0,nop); // dpl <- T	

    // await interrupt
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_rtc); // jump to rtc_60s  1/60th second	
	ins6(delay_m,nop,nop,nop,nop,nop);
    print_cycles();	
	//------------------------------
	opcode_page(page_rtc, rtc_exit, 'rtc_exit', nop, nop); // 23-9-2025 determines what happens after the clock did a tick
	
	// check reg_kb_state. bit7=1 -> V_IWAIT, bit7=0 -> rtc_shutdn

	make_literal(to_t,rtc_shutdn);	// 15-8-2025 T <- rtc_shutdn

	ins6(nop,to_dpl,asl,acc_t,reg_kb_state,nop); // get bit7 to tc, result to dpl (unused)
	ins6(tc_to_f,to_dpl,xor,acc_t,lit0,nop); // dpl <- T, F <- tc
	
	if_f_t( in_f(nop,to_t,add,acc_t,lit0,nop),                  // 0:  nop
	        in_t(nop, to_t, ld_ir, acc_t, lit40, page_reset) ); // 1:  jp to exit (V_IWAIT)
	ins6(nop,to_t,add,acc_t,lit0,nop); // nop

	// put constant in BC
	make_literal(to_t,0xB9);
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);          // reg_c <- T
	make_literal(to_t,0x65);
	
	ins6(nop, to_t, ld_ir, acc_t, dpl, page_rtc); //jp to rtc_shutdn (#0)
	ins6(nop, to_mem, ld, acc_t, reg_b, nop);          // reg_b <- T	

	print_cycles();	
	//------------------------------
	opcode_page(page_rtc, rtc_shutdn, 'rtc_shutdn', nop, nop); // 23-9-2025 during shutdn, this counts until 1/60th second

	// The loop is 8 cycles.
	// 1/60th sec is 12500000/60 = 208333 cycles. Divided by 8 is 26041 (hex 65B9)

	// now dec BC
	ins6(nop, to_t, dec, acc_t, reg_c, nop);		   // T <- reg_c -1
	ins6(nop, to_mem, ld, acc_t, reg_c, nop);          // reg_c <- T
	ins6(nop, to_t, dec_dtc, acc_t, reg_b, nop);       // T reg_b - 1 (if there was a cy)
	ins6(tc_to_f, to_mem, ld, acc_t, reg_b, nop);      // reg_b <- T , F <- tc
	
	// F=0: end of loop, to rtc_60S 0x1A    F=1: stay in loop, to rtc_shutdn 0x18

	if_f_t( in_f(nop, to_t, inc, acc_t, lit9, nop),   // 0:  T <- 0x0A
	        in_t(nop, to_t, ld,  acc_t, lit8, nop) ); // 1:  T <- 0x08

	ins6(nop,to_dpl,add,acc_t,lit16,nop); // dpl <- T + 0x10

	ins6(nop, to_t, ld_ir, acc_t, dpl, page_rtc); // jp to dpl
	ins6(nop,to_t,add,acc_t,lit0,nop); // nop

	print_cycles();
	//------------------------------
	//opcode_page(page_rtc, 0xEA, 'rtc_60s', nop, nop); // jump to here to count a new 1/60 second
	opcode_page(page_rtc, 0x1A, 'rtc_60s', nop, nop); // 15-8-2025 jump to here to count a new 1/60 second


	ins6(nop,to_dpl,inc,acc_t,lit1,nop);   // time_60s = 2
	ins6(nop,to_dph,inc,acc_t,lit4,nop);   // time_msb = 5

	make_literal(to_t,59);
	testlimit(lit0);  // if 59 reached, reset counter and continue. else, increment it and jp to exit
	//--------------
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // inc dpl to seconds
	make_literal(to_t,59);
	testlimit(lit0);  // if 59 reached, reset counter and continue. else, increment it and jp to exit
	//--------------
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // inc dpl to minutes
	make_literal(to_t,59);
	testlimit(lit0);  // if 59 reached, reset counter and continue. else, increment it and jp to exit
	//--------------
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // inc dpl to hours
	make_literal(to_t,23);
	testlimit(lit0);  // if 23 reached, reset counter and continue. else, increment it and jp to exit
	//--------------
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // set dpl to months = 7
	make_literal(to_t,2); // month 2 (february)
	ins6(nop,to_t,xor_tst,acc_t,ext,time_bnk);  //compare month counter with 2
	ins6(tc_to_f,to_t,xor,acc_t,lit0,nop);  // nop, tc_to_f	

	// Now calculate the number of days that this month has, F=0: Februari  F=1: non-February

	if_f_t( in_f(nop,to_dpl,ld,acc_t,lit8,nop),    //  FEB: time_year = 8 
	        in_t(nop,to_t,ld,acc_t,lit8,nop));     // non-FEB: set T = 8

	if_f_t( in_f(nop,to_t,dec,acc_t,lit4,nop), // FEB: set T = 3
			in_t(nop,to_t,and_tst,acc_t,ext,time_bnk));  // non-FEB: test bit 3 of  month counter

	if_f_t( in_f(nop,to_t,and_tst,acc_t,ext,time_bnk),  // FEB: test lower 2 bits of year. set TC if not a leap year
			in_t(nop,to_t,inc_tc,acc_t,ext,time_bnk)); // non-FEB:  get month nr, but increment it for august or later

	if_f_t( in_f(nop,to_t,inc_tc,acc_t,lit32,nop), // FEB: load 32 (leap yr) or 33 (not leap yr)
			in_t(nop,to_t,and,acc_t,lit1,nop)); // non-FEB: select only bit 0. 1: 31 days, 0: 30 days	

	if_f_t( in_f(nop,to_t,xor,acc_t,lit1,nop),  // FEB: toggle bit 0: 32 (not leap yr) or 33 (leap yr)
			in_t(nop,to_t,add,acc_t,reg_0F,nop)); // non-FEB: 

	if_f_t(	in_f(nop,to_t,sub,acc_t,lit4,nop),  // FEB: subtract 4:  28 (not leap yr) or 29 (leap yr)
			in_t(nop,to_t,add,acc_t,reg_0F,nop)); // non-FEB: two times add 15, makes 30 or 31 days as limit

	ins6(nop,to_dpl,inc,acc_t,lit4,nop);   // five
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // 5+1 = 6. time_days = 6	
	testlimit(lit1);  // if limit reached, reset counter to day 1 and continue. else, increment it and jp to exit
	//--------------
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // inc dpl to months
	make_literal(to_t,12);
	testlimit(lit1);  // if 12 reached, reset counter to month 1 and continue. else, increment it and jp to exit
	//--------------
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // inc dpl to years
	make_literal(to_t,0);
	testlimit(lit0);  // if 0 reached, reset counter to 0 and continue. else, increment it and jp to exit
	//--------------
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // inc dpl to years256
	make_literal(to_t,0);
	testlimit(lit0);  // if 0 reached, reset counter to 0 and continue. else, increment it and jp to exit

	ins6(nop, to_t, ld_ir, acc_t, lit40, page_reset); //jp to exit after year 65535

    print_cycles();	
	//------------------------------
	opcode_page(page_in, port_io_rtc_read, 'rtc_read', nop, nop); //

	ins6(nop, to_t, ld, acc_t, pcl, nop);		// get pcl move it to t
	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // store pcl in reg_tl temporary location
    ins6(nop, to_pch, ld, acc_t, reg_l, nop);   // write reg_l to pch to get pch into pcl
	ins6(nop, to_t, ld, acc_t, pcl, nop); // t <- pcl (this is actuall pc-msb)
	ins6(nop, to_mem, ld, acc_t, reg_th, nop); // store pcl in reg_th temporary location		
    ins6(nop, to_pch, ld, acc_t, reg_h, nop);   // write reg_h to pch

	ins6(nop,to_dpl,dec,acc_t,lit4,nop);   // time_secs = 3
	ins6(nop,to_dph,inc,acc_t,lit4,nop);   // time_msb = 5

	i=1; while (i<=8) { // sec, min, hours, days, months, years, years256, magic_nr
		ins6(nop,to_t,ld,acc_t,ext,time_bnk); // get time byte  time_secs
		ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // inc dpl
		ins6(nop,to_mem,ld,acc_t,pc_pp,nop); // write it to (pc++)
	    i++; }

    ins6(nop, to_pch, ld, acc_t, reg_tl, nop);   // restore reg_l to pch

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp back to current isa
    ins6(nop, to_pch, ld, acc_t, reg_th, nop);   // restore reg_h to pch	
    print_cycles();		

	//------------------------------
	opcode_page(page_out, port_io_rtc_write, 'rtc_write', nop, nop); //

	ins6(nop, to_t, ld, acc_t, pcl, nop);		// get pcl move it to t
	ins6(nop, to_mem, ld, acc_t, reg_tl, nop); // store pcl in reg_tl temporary location
    ins6(nop, to_pch, ld, acc_t, reg_l, nop);   // write reg_l to pch to get pch into pcl
	ins6(nop, to_t, ld, acc_t, pcl, nop); // t <- pcl (this is actuall pc-msb)
	ins6(nop, to_mem, ld, acc_t, reg_th, nop); // store pcl in reg_th temporary location		
    ins6(nop, to_pch, ld, acc_t, reg_h, nop);   // write reg_h to pch
 
	ins6(nop,to_dpl,inc,acc_t,lit1,nop);   // time_60s = 2
	ins6(nop,to_dph,inc,acc_t,lit4,nop);   // time_msb = 5	

	ins6(nop, to_t, ld, acc_t, lit0, nop);	 // T = 0
	ins6(nop,to_mem,ld,acc_t,ext,time_bnk); // write time byte per 1/60 sec
	ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // inc dpl

	i=1; while (i<=8) { // sec, min, hours, days, months, years, years256, magic_nr
		ins6(nop,to_t,ld,acc_t,pc_pp,nop); // get time byte from (pc++)
		ins6(nop,to_mem,ld,acc_t,ext,time_bnk); // write time byte  time_secs
		ins6(nop,to_dpl,inc,acc_t,dpl,nop);   // inc dpl
	    i++; }

    ins6(nop, to_pch, ld, acc_t, reg_tl, nop);   // restore reg_l to pch

	ins6(l_to_f, to_t, ld_ir, acc_t, reg_isa, page_reset); // jp back to current isa
    ins6(nop, to_pch, ld, acc_t, reg_th, nop);   // restore reg_h to pch	
    print_cycles();		

  }



function build_microcode() {

	// This will give instructions like this:

	// source: https://www.masswerk.at/6502/6502_instruction_set.html

	commentline_init();  // 15-8-2025
	

	//-----------------------------------------------------------------
	//
	//	6502 Instructions
	//
	//-----------------------------------------------------------------

	commentline("");
	commentline("Isetta 6502/Z80 microcode by Roelh, " + thisdate);


    /*
	commentline("");
	commentline("--------------  MICROCODE  REGISTERS  ---------------");
	commentline("");
    list_registers();
    */


	build_rtc(); // 8-8-2025


	if (generate_undefined == 1)
	{

	commentline("");
	commentline("------  U N D E F I N E D    I N S T R U C T I O N S  -------");
	commentline("");

	instruction_counter = 0; error_m_count = 0;

    // 27-2-2025 catch jumps to undefined microcode
	
	isetta_undef(page_reset,0,0x15);  // skip the area where VAL or DATA is.
	isetta_undef(page_reset,0x1F,0xBF);
	isetta_undef(page_reset,0xE4,0xEF);	

	isetta_undef(page_z80_ix,0x00,0xFF); // 10-3-2025
	isetta_undef(page_z80_iy,0x00,0xFF); // 10-3-2025	
	
	isetta_undef(page_hires,0x00,0xFF);	

    handle_undef(0x0F,"UNDEF");

	}  // endif generate_undefined



	page_default = page_6502;
	
	comp_val[next_m] = comp_val[ld_ir] | comp_val[pc_pp] | comp_val[page_6502] ; // 23-12-2024
	comp_val[interrupt_m] = con6(nop, to_t, ld_ir, acc_t, reg_128, page_6502);
	comp_val[delay_m] = con6(irq_to_f, to_t, xor, acc_t, lit0, nop); // 20-7-2023



	if (generate_blitter == 1)
	{	
	commentline("");
	commentline("--------------  C O L O R   C O N V E R S I O N   ---------------");
	commentline("");

	make_color_conversion();
	make_cp_u_table(); // 9-4-2025
	} // endif generate-blitter



	instruction_counter = 0; error_m_count = 0;

	if (generate_6502 == 1)
	{

	commentline("");
	commentline("--------------  6 5 0 2 _ I N S T R U C T I O N S  ---------------");
	commentline("");


	commentline(""); commentline("------  6502 Load and store ------"); commentline("");

	ins_ld(0xA9, 'LDA', reg_a, imm); // all set NZ
	ins_ld(0xA5, 'LDA', reg_a, zp);
	ins_ld(0xB5, 'LDA', reg_a, zpx);
	ins_ld(0xAD, 'LDA', reg_a, abs);
	ins_ld(0xBD, 'LDA', reg_a, absx);
	ins_ld(0xB9, 'LDA', reg_a, absy);
	ins_ld(0xA1, 'LDA', reg_a, idx);
	ins_ld(0xB1, 'LDA', reg_a, idy);

	ins_ld(0xA2, 'LDX', reg_x, imm); // all set NZ
	ins_ld(0xA6, 'LDX', reg_x, zp);
	ins_ld(0xB6, 'LDX', reg_x, zpy);
	ins_ld(0xAE, 'LDX', reg_x, abs);
	ins_ld(0xBE, 'LDX', reg_x, absy);

	ins_ld(0xA0, 'LDY', reg_y, imm); // all set NZ
	ins_ld(0xA4, 'LDY', reg_y, zp);
	ins_ld(0xB4, 'LDY', reg_y, zpx);
	ins_ld(0xAC, 'LDY', reg_y, abs);
	ins_ld(0xBC, 'LDY', reg_y, absx);

	ins_st(0x85, 'STA', reg_a, zp); // no flags affected
	ins_st(0x95, 'STA', reg_a, zpx);
	ins_st(0x8D, 'STA', reg_a, abs);
	ins_st(0x9D, 'STA', reg_a, absx);
	ins_st(0x99, 'STA', reg_a, absy);
	ins_st(0x81, 'STA', reg_a, idx);
	ins_st(0x91, 'STA', reg_a, idy);

	ins_st(0x86, 'STX', reg_x, zp);
	ins_st(0x96, 'STX', reg_x, zpy);
	ins_st(0x8E, 'STX', reg_x, abs);

	ins_st(0x84, 'STY', reg_y, zp);
	ins_st(0x94, 'STY', reg_y, zpx);
	ins_st(0x8C, 'STY', reg_y, abs);

	commentline(""); commentline("------  6502 Register transfer  ------"); commentline("");

	ins_taxy(0xAA, 'TAX', reg_a, reg_x, upd_nz); // transfer A to X  30-11 old name: ins_stf
	ins_taxy(0xA8, 'TAY', reg_a, reg_y, upd_nz);
	ins_ld(0x8A, 'TXA', reg_a, reg_x);
	ins_ld(0x98, 'TYA', reg_a, reg_y);

	ins_tr(0xBA, 'TSX', reg_s, reg_x, upd_nz);
	ins_tr(0x9A, 'TXS', reg_x, reg_s, nop); // txs (to S) sets no flags, all other transfers do set NZ

	commentline(""); commentline("------  6502 Increments and decrements  ------"); commentline("");

	ins_dec(0xC6, 'DEC', zp); // all set NZ
	ins_dec(0xD6, 'DEC', zpx);
	ins_dec(0xCE, 'DEC', abs);
	ins_dec(0xDE, 'DEC', absx);
	ins_dec(0xCA, 'DEX', reg_x);
	ins_dec(0x88, 'DEY', reg_y);

	ins_inc(0xE6, 'INC', zp); // all set NZ
	ins_inc(0xF6, 'INC', zpx);
	ins_inc(0xEE, 'INC', abs);
	ins_inc(0xFE, 'INC', absx);
	ins_inc(0xE8, 'INX', reg_x);
	ins_inc(0xC8, 'INY', reg_y);

	commentline(""); commentline("------  6502 Arithmetic  ------"); commentline("");

	ins_adc(0x69, 'ADC', imm); // all set NZCV
	ins_adc(0x65, 'ADC', zp);
	ins_adc(0x75, 'ADC', zpx);
	ins_adc(0x6D, 'ADC', abs);
	ins_adc(0x7D, 'ADC', absx);
	ins_adc(0x79, 'ADC', absy);
	ins_adc(0x61, 'ADC', idx);
	ins_adc(0x71, 'ADC', idy);

	ins_sbc(0xE9, 'SBC', imm); // all set NZCV
	ins_sbc(0xE5, 'SBC', zp);
	ins_sbc(0xF5, 'SBC', zpx);
	ins_sbc(0xED, 'SBC', abs);
	ins_sbc(0xFD, 'SBC', absx);
	ins_sbc(0xF9, 'SBC', absy);
	ins_sbc(0xE1, 'SBC', idx);
	ins_sbc(0xF1, 'SBC', idy);

	commentline(""); commentline("------  6502 Logic  ------"); commentline("");

	ins_and(0x29, 'AND', imm); // all set NZ
	ins_and(0x25, 'AND', zp);
	ins_and(0x35, 'AND', zpx);
	ins_and(0x2D, 'AND', abs);
	ins_and(0x3D, 'AND', absx);
	ins_and(0x39, 'AND', absy);
	ins_and(0x21, 'AND', idx);
	ins_and(0x31, 'AND', idy);

	ins_eor(0x49, 'EOR', imm); // all set NZ
	ins_eor(0x45, 'EOR', zp);
	ins_eor(0x55, 'EOR', zpx);
	ins_eor(0x4D, 'EOR', abs);
	ins_eor(0x5D, 'EOR', absx);
	ins_eor(0x59, 'EOR', absy);
	ins_eor(0x41, 'EOR', idx);
	ins_eor(0x51, 'EOR', idy);

	ins_ora(0x09, 'ORA', imm); // all set NZ
	ins_ora(0x05, 'ORA', zp);
	ins_ora(0x15, 'ORA', zpx);
	ins_ora(0x0D, 'ORA', abs);
	ins_ora(0x1D, 'ORA', absx);
	ins_ora(0x19, 'ORA', absy);
	ins_ora(0x01, 'ORA', idx);
	ins_ora(0x11, 'ORA', idy);

	commentline(""); commentline("------  6502 Shift and rotate  ------"); commentline("");

	ins_asl(0x0A, 'ASL', reg_a);	// C <- [76543210] <- 0
	ins_asl(0x06, 'ASL', zp);
	ins_asl(0x16, 'ASL', zpx);		// // all set NZC
	ins_asl(0x0E, 'ASL', abs);
	ins_asl(0x1E, 'ASL', absx);

	ins_lsr(0x4A, 'LSR', reg_a);  	// 0 -> [76543210] -> C
	ins_lsr(0x46, 'LSR', zp);
	ins_lsr(0x56, 'LSR', zpx);		// all set NZC  (N=0)
	ins_lsr(0x4E, 'LSR', abs);
	ins_lsr(0x5E, 'LSR', absx);

	ins_rol(0x2A, 'ROL', reg_a);  	// C <- [76543210] <- C
	ins_rol(0x26, 'ROL', zp);
	ins_rol(0x36, 'ROL', zpx);		// all set NZC 
	ins_rol(0x2E, 'ROL', abs);
	ins_rol(0x3E, 'ROL', absx);

	ins_ror(0x6A, 'ROR', reg_a);  	// C -> [76543210] -> C
	ins_ror(0x66, 'ROR', zp);
	ins_ror(0x76, 'ROR', zpx);		// all set NZC 
	ins_ror(0x6E, 'ROR', abs);
	ins_ror(0x7E, 'ROR', absx);

	commentline(""); commentline("------  6502 Compare  ------"); commentline("");

	ins_cmp(0xC9, 'CMP', reg_a, imm); // all set NZC
	ins_cmp(0xC5, 'CMP', reg_a, zp);
	ins_cmp(0xD5, 'CMP', reg_a, zpx);
	ins_cmp(0xCD, 'CMP', reg_a, abs);
	ins_cmp(0xDD, 'CMP', reg_a, absx);
	ins_cmp(0xD9, 'CMP', reg_a, absy);
	ins_cmp(0xC1, 'CMP', reg_a, idx);
	ins_cmp(0xD1, 'CMP', reg_a, idy);

	ins_cmp(0xE0, 'CPX', reg_x, imm);
	ins_cmp(0xE4, 'CPX', reg_x, zp);  // all set NZC
	ins_cmp(0xEC, 'CPX', reg_x, abs);

	ins_cmp(0xC0, 'CPY', reg_y, imm);
	ins_cmp(0xC4, 'CPY', reg_y, zp);  // all set NZC
	ins_cmp(0xCC, 'CPY', reg_y, abs);

	commentline(""); commentline("------  6502 Conditional branch  ------"); commentline("");

	ins_brcond(0x90, 'BCC', c_to_f, false); // branch on carry clear
	ins_brcond(0xB0, 'BCS', c_to_f, true);  // branch on carry set

	ins_brcond(0xF0, 'BEQ', z_to_f, true);  // branch on equal (Z=1)
	ins_brcond(0xD0, 'BNE', z_to_f, false); // branch on not equal (Z=0)

	ins_brcond(0x30, 'BMI', n_to_f, true);  // branch on minus (N=1)
	ins_brcond(0x10, 'BPL', n_to_f, false); // branch on positive (N=0)

	ins_brcond(0x50, 'BVC', flag_v, false); // branch on overflow clear (V=0)
	ins_brcond(0x70, 'BVS', flag_v, true);  // branch on overflow set (V=1)
	// 19-6 use again
	ins_brcond(0x04, 'BFC', nop, false); // branch on F=0, for overflow clear (V=0)
	ins_brcond(0x14, 'BFS', nop, true);  // branch on F=1, for overflow set (V=1)

	// Next instructions are used to calculate the V flag
	// The BVC and BVS will jump to these instructions.
	// Explained here: http://6502.org/users/dieter/v_flag/v_3.htm
	// The 3 following bits in the opcode are the input bits.
	// bit0: Q7  bit4: A7  bit5: B7   
	// If Q7 = 0, then V is set if A7 and B7 both 1
	// If Q7 = 1, then V is set if A7 and B7 both 0

	ins_vcalc(0x02, 'V0x02', false);
	ins_vcalc(0x03, 'V0x03', true); // true
	ins_vcalc(0x12, 'V0x12', false);
	ins_vcalc(0x13, 'V0x13', false);
	ins_vcalc(0x22, 'V0x22', false);
	ins_vcalc(0x23, 'V0x23', false);
	ins_vcalc(0x32, 'V0x32', true); // true
	ins_vcalc(0x33, 'V0x33', false);

	commentline(""); commentline("------  6502 Stack  ------"); commentline("");

	ins_pha(0x48, 'PHA');
	ins_pla(0x68, 'PLA');
	ins_php(0x08, 'PHP');
	ins_plp(0x28, 'PLP');

	commentline(""); commentline("------  6502 Jumps and subroutines  ------"); commentline("");

	ins_jmp(0x4C, 'JMP', abs);
	ins_jmp(0x6C, 'JMP', ind);
	ins_jsr(0x20, 'JSR', abs);
	ins_rcal(page_reset, 0x08, 'RCAL'); // 13-11-2023
	ins_rts(0x60, 'RTS');  // 

	ins_nop(0x00, 'BRK'); // not implemented yet
	ins_nop(0x40, 'RTI'); // not implemented yet

	commentline(""); commentline("------  6502 Flags set, reset and test  ------"); commentline("");

	ins_clc(0x18, 'CLC'); // clear carry flag
	ins_sec(0x38, 'SEC'); // set carry flag

	ins_nop(0xD8, 'CLD'); // clear decimal flag
	ins_nop(0xF8, 'SED'); // set decimal flag

	ins_nop(0x58, 'CLI');
	ins_nop(0x78, 'SEI');

	ins_clv(0xB8, 'CLV'); // clear overflow flag

	ins_bit(0x24, 'BIT', zp);
	ins_bit(0x2C, 'BIT', abs);

	ins_nop(0xEA, 'NOP');

	ins_int6502(0x80, 'INT'); // interrupt  19-6 was 0x02
	ins_inr6(0x05, 'INR6'); // interrupt, retries same instruction (does pc-2)   

	ins_in(0xDB, 'IN');   // 5-3-2024
	ins_out(0xD3, 'OUT');  // 5-3-2024   

	// end of 6502 instructions

	commentline("");
	commentline(instruction_counter + " opcodes generated for 6502.");
	commentline(error_m_count + " errors.");

	}  // endif generate_6502


	// check online simulator 6502: https://itema-as.github.io/6502js/

	// or:  https://macgui.com/downloads/?file_id=8091  Apple II simulator

	instruction_counter = 0; error_m_count = 0;

	if (generate_Z80 == 1)
	{	


	commentline("--------------  Z 8 0 _ I N S T R U C T I O N S  ---------------");
	commentline("");


	const reg_list = [reg_b, reg_c, reg_d, reg_e, reg_h, reg_l, ind_hl, reg_a];  // 0 - 7

	const op_list = [add, adc, sub, sbc, and, xor, or, cp];  // 0 - 7
	var i = 0; var j = 0;

	page_default = page_z80;
	
	comp_val[next_m] = comp_val[ld_ir] | comp_val[pc_pp] | comp_val[page_z80] ; // 23-12-2024	
	comp_val[interrupt_m] = con6(nop, to_t, ld_ir, acc_t, reg_128, page_z80_ed);


	commentline(""); commentline("------  Z80 8-bit load  ------"); commentline("");


	for (i = 0; i <= 7; i++) { z80_ins8(0x06 + (i << 3), 'LD', ld, reg_list[i], imm, nop); } // ld imm reg8

	z80_ins8(0x3A, 'LD', ld, reg_a, abs, nop);    // ld a,(abs)
	z80_ins8(0x0A, 'LD', ld, reg_a, ind_bc, nop); // ld a,(bc)
	z80_ins8(0x1A, 'LD', ld, reg_a, ind_de, nop); // ld a,(de)
	z80_ins8(0x32, 'LD', ld, abs, reg_a, nop);    // ld (abs),a
	z80_ins8(0x02, 'LD', ld, ind_bc, reg_a, nop); // ld (bc),a
	z80_ins8(0x12, 'LD', ld, ind_de, reg_a, nop); // ld (de),a

	// 64 r-to-r ld instructions

	for (i = 0; i <= 7; i++) for (j = 0; j <= 7; j++) {
		if (i == j) {
			if (reg_list[i] != ind_hl)
				ins_nop(0x040 + (i << 3) + j, 'NOP'); // ld register into same register
		}
		else z80_ins8(0x040 + (i << 3) + j, 'LD', ld, reg_list[i], reg_list[j], nop);
	}

	commentline(""); commentline("------  Z80 8-bit arithmetic and logic  ------"); commentline("");

	for (i = 0; i <= 7; i++) { z80_ins8(0x04 + (i << 3), 'INC', inc, reg_list[i], nop, upd_nz); } // inc reg8

	for (i = 0; i <= 7; i++) { z80_ins8(0x05 + (i << 3), 'DEC', dec, reg_list[i], nop, upd_nz); } // dec reg8

	for (i = 0; i <= 7; i++) // All arithmetic/logic with immediate 8-bit operand
	{ z80_ins8(0x0C6 + (i << 3), comp_name[op_list[i]], op_list[i], reg_a, imm, upd_nzc); }

	// 64 operations: all 8 registers combined with all 8 operations

	for (i = 0; i <= 7; i++) for (j = 0; j <= 7; j++) { z80_ins8(0x080 + (i << 3) + j, comp_name[op_list[i]], op_list[i], reg_a, reg_list[j], upd_nzc); }


	commentline(""); commentline("------  Z80 8-bit shift  ------"); commentline("");

	z80_ins8(0x17, 'RLA', rla, reg_a, nop, upd_c);
	z80_ins8(0x07, 'RLCA', rlca, reg_a, nop, upd_c);
	z80_ins8(0x1F, 'RRA', rra, reg_a, nop, upd_c);
	z80_ins8(0x0F, 'RRCA', rrca, reg_a, nop, upd_c);

	// shifts in CB group

	for (i = 0; i <= 7; i++) {
		z80_gen8(page_z80_cb, 0x00 + i, 'RLC', rlc, reg_list[i], nop, upd_nzc);
		z80_gen8(page_z80_cb, 0x08 + i, 'RRC', rrc, reg_list[i], nop, upd_nzc);
		z80_gen8(page_z80_cb, 0x10 + i, 'RL', rl, reg_list[i], nop, upd_nzc);
		z80_gen8(page_z80_cb, 0x18 + i, 'RR', rr, reg_list[i], nop, upd_nzc);

		z80_gen8(page_z80_cb, 0x20 + i, 'SLA', sla, reg_list[i], nop, upd_nzc);
		z80_gen8(page_z80_cb, 0x28 + i, 'SRA', sra, reg_list[i], nop, upd_nzc);
		z80_gen8(page_z80_cb, 0x38 + i, 'SRL', srl, reg_list[i], nop, upd_nzc);
	}

	z80_rrd(page_z80_ed, 0x67, "RRD");  // 23-6-2024
	z80_rld(page_z80_ed, 0x6F, "RLD");  // 23-6-2024


	commentline(""); commentline("------  Z80 bit test, set and reset  ------"); commentline("");

	for (i = 0; i <= 7; i++) for (j = 0; j <= 7; j++) {
		z80_gen8(page_z80_cb, 0x40 + (j << 3) + i, 'BIT', z80_bit, bitnr0 + j, reg_list[i], upd_z);
		z80_gen8(page_z80_cb, 0x80 + (j << 3) + i, 'RES', z80_res, bitnr0 + j, reg_list[i], nop);
		z80_gen8(page_z80_cb, 0xC0 + (j << 3) + i, 'SET', z80_set, bitnr0 + j, reg_list[i], nop);
	}


	commentline(""); commentline("------  Z80 16-bit load  ------"); commentline("");

	z80_ins16(0x01, 'LD', ld, pair_bc, imm, nop);
	z80_ins16(0x11, 'LD', ld, pair_de, imm, nop);
	z80_ins16(0x21, 'LD', ld, pair_hl, imm, nop);
	z80_ins16(0x31, 'LD', ld, pair_sp, imm, nop);

	z80_ins16(0x2A, 'LD', ld, pair_hl, abs, nop);
	z80_ins16(0x22, 'LD', ld, abs, pair_hl, nop);

	z80_ins16(0xF9, 'LD', ld, pair_sp, pair_hl, nop);

	// ED page instructions
	z80_gen16(page_z80_ed, 0x4B, 'LD', ld, pair_bc, abs, nop);
	z80_gen16(page_z80_ed, 0x5B, 'LD', ld, pair_de, abs, nop);
	z80_gen16(page_z80_ed, 0x7B, 'LD', ld, pair_sp, abs, nop);

	z80_gen16(page_z80_ed, 0x43, 'LD', ld, abs, pair_bc, nop);
	z80_gen16(page_z80_ed, 0x53, 'LD', ld, abs, pair_de, nop);
	z80_gen16(page_z80_ed, 0x73, 'LD', ld, abs, pair_sp, nop);

	z80_gen16(page_z80_ed, 0x7F, 'LD', ld, abs, pair_th_tl, nop);	// 11-1-2025 store pc addr for debugging

	z80_ins16(0xC5, 'PUSH', push, pair_bc, nop, nop);
	z80_ins16(0xD5, 'PUSH', push, pair_de, nop, nop);
	z80_ins16(0xE5, 'PUSH', push, pair_hl, nop, nop);
	z80_ins16(0xF5, 'PUSH', push, pair_af, nop, nop);

	z80_ins16(0xC1, 'POP', pop, pair_bc, nop, nop);
	z80_ins16(0xD1, 'POP', pop, pair_de, nop, nop);
	z80_ins16(0xE1, 'POP', pop, pair_hl, nop, nop);
	z80_ins16(0xF1, 'POP', pop, pair_af, nop, nop);

	z80_gen16(page_z80, 0xEB, 'EX', ex, pair_de, pair_hl, nop); // EX DE,HL  // no IX, IY version

	z80_ins16(0xE3, 'EX', ex, ind_sp, pair_hl, nop);  // EX (SP),HL  // has IX, IY version

	z80_ins16(0x08, 'EX', ex, pair_af, pair_af, nop);  // EX AF,AF'

	commentline(""); commentline("----  Z80 16-bit arithmetic  ----"); commentline("");

	z80_ins16(0x03, 'INC', inc, pair_bc, nop, nop);  // no flag updates for 16bit inc/dec
	z80_ins16(0x13, 'INC', inc, pair_de, nop, nop);
	z80_ins16(0x23, 'INC', inc, pair_hl, nop, nop);
	z80_ins16(0x33, 'INC', inc, pair_sp, nop, nop);
	z80_ins16(0x0B, 'DEC', dec, pair_bc, nop, nop);
	z80_ins16(0x1B, 'DEC', dec, pair_de, nop, nop);
	z80_ins16(0x2B, 'DEC', dec, pair_hl, nop, nop);
	z80_ins16(0x3B, 'DEC', dec, pair_sp, nop, nop);

	z80_ins16(0x09, 'ADD', add, pair_hl, pair_bc, upd_c);
	z80_ins16(0x19, 'ADD', add, pair_hl, pair_de, upd_c);
	z80_ins16(0x29, 'ADD', add, pair_hl, pair_hl, upd_c);
	z80_ins16(0x39, 'ADD', add, pair_hl, pair_sp, upd_c);

	// ED group instructions
	z80_gen16(page_z80_ed, 0x4A, 'ADC', adc, pair_hl, pair_bc, upd_nzc);
	z80_gen16(page_z80_ed, 0x5A, 'ADC', adc, pair_hl, pair_de, upd_nzc);
	z80_gen16(page_z80_ed, 0x6A, 'ADC', adc, pair_hl, pair_hl, upd_nzc);
	z80_gen16(page_z80_ed, 0x7A, 'ADC', adc, pair_hl, pair_sp, upd_nzc);

	z80_gen16(page_z80_ed, 0x42, 'SBC', sbc, pair_hl, pair_bc, upd_nzc);
	z80_gen16(page_z80_ed, 0x52, 'SBC', sbc, pair_hl, pair_de, upd_nzc);
	z80_gen16(page_z80_ed, 0x62, 'SBC', sbc, pair_hl, pair_hl, upd_nzc);
	z80_gen16(page_z80_ed, 0x72, 'SBC', sbc, pair_hl, pair_sp, upd_nzc);

	commentline(""); commentline("------  Z80 Jump, Call and Return  ------"); commentline("");

	// conditional branches. Similar to those on the 6502

	ins_brcond(0x18, 'JR', l_to_f, false);  // branch always.
	ins_brcond(0x20, 'JR NZ', z_to_f, false);  // branch on not equal (Z=0)
	ins_brcond(0x28, 'JR Z', z_to_f, true);   // branch on equal (Z=1)
	ins_brcond(0x30, 'JR NC', c_to_f, false);  // branch on carry clear
	ins_brcond(0x38, 'JR C', c_to_f, true);   // branch on carry set

	ins_brcond(0x10, 'DJNZ', z_to_f, false);   // 10-11-2023 djnz handled by branch-conditional

	z80_ins16(0xE9, 'LD', ld, pair_pc, pair_hl, nop); // JP (HL)

	z80_jmp(page_z80, 0xC3, 'JP', l_to_f, false); // 10-11-2023 JP handled by conditional jp

	z80_jmp(page_z80, 0xC2, 'JP NZ', z_to_f, false);
	z80_jmp(page_z80, 0xCA, 'JP Z', z_to_f, true);
	z80_jmp(page_z80, 0xD2, 'JP NC', c_to_f, false);
	z80_jmp(page_z80, 0xDA, 'JP C', c_to_f, true);

	z80_jmp(page_z80, 0xE2, 'JP PO', flag_v, false); // jp on parity odd, no overflow
	z80_jmp(page_z80, 0xEA, 'JP PE', flag_v, true);  // jp on parity even, overflow

	z80_jmp(page_z80, 0xF2, 'JP P', n_to_f, false);  // jp if positive
	z80_jmp(page_z80, 0xFA, 'JP M', n_to_f, true);   // jp if negative

	// Next instructions are used to calculate the V flag, in the same way as for 6502.

	ins_vcalc_z80(0x02, 'V0x02', false);
	ins_vcalc_z80(0x03, 'V0x03', true); // true
	ins_vcalc_z80(0x12, 'V0x12', false);
	ins_vcalc_z80(0x13, 'V0x13', false);
	ins_vcalc_z80(0x22, 'V0x22', false);
	ins_vcalc_z80(0x23, 'V0x23', false);
	ins_vcalc_z80(0x32, 'V0x32', true); // true
	ins_vcalc_z80(0x33, 'V0x33', false);

	z80_jmp(page_z80_ed, 0x04, 'JP FC', nop, false);  // jp if F=0, overflow test. (On ED page)
	z80_jmp(page_z80_ed, 0x14, 'JP FS', nop, true);   // jp if F=1, overflow test. (On ED page)

	z80_call(0xCD, 'CALL', l_to_f, false);

	z80_call(0xC4, 'CALL NZ', z_to_f, false);
	z80_call(0xCC, 'CALL Z', z_to_f, true);
	z80_call(0xD4, 'CALL NC', c_to_f, false);
	z80_call(0xDC, 'CALL C', c_to_f, true);
	//  z80_call(0xE4,'CALL PO',h_to_f,false) ; // parity not implemented, always 1
	//  z80_call(0xEC,'CALL PE',h_to_f,true) ;
	z80_call(0xF4, 'CALL P', n_to_f, false);  // call if positive
	z80_call(0xFC, 'CALL M', n_to_f, true);   // call if negative

	z80_stsp(page_z80_ix, 0x08, 'STSP');   // 21-11-2023
	z80_calr(page_z80_ix, 0x04, 'CALR'); // 8-11-2023

	z80_ret(0xC9, 'RET', l_to_f, false);

	z80_ret(0xC0, 'RET NZ', z_to_f, false);
	z80_ret(0xC8, 'RET Z', z_to_f, true);
	z80_ret(0xD0, 'RET NC', c_to_f, false);
	z80_ret(0xD8, 'RET C', c_to_f, true);
	//  z80_ret(0xE0,'RET PO',h_to_f,false) ; // parity not implemented, always 1
	//  z80_ret(0xE8,'RET PE',h_to_f,true) ;
	z80_ret(0xF0, 'RET P', n_to_f, false);  // return if positive
	z80_ret(0xF8, 'RET M', n_to_f, true);   // return if negative

	z80_restart(0xC7, 'RST 0x00', 0);
	z80_restart(0xCF, 'RST 0x08', 1);
	z80_restart(0xD7, 'RST 0x10', 2);
	z80_restart(0xDF, 'RST 0x18', 3);
	z80_restart(0xE7, 'RST 0x20', 4);
	z80_restart(0xEF, 'RST 0x28', 5);
	z80_restart(0xF7, 'RST 0x30', 6);
	z80_restart(0xFF, 'RST 0x38', 7);	


	commentline(""); commentline("------  Z80 CPU Block transfer and search  ------"); commentline("");

	z80_ldi(page_z80_ed, 0xA0, "LDI");  // 22-6-2024
	z80_ldd(page_z80_ed, 0xA8, "LDD");  // 30-6-2024	

	z80_gen16(page_z80_ix, 0x40, 'DEC', dec, pair_bc, nop, nop); // a copy of DEC BC, used by LDI and LDD  6-3-2025

	z80_cpi(page_z80_ed, 0xA1, "CPI");  // 16-9-2024
	z80_cpd(page_z80_ed, 0xA9, "CPD");  // 16-9-2024		

	z80_ldir(page_z80_ed, 0xB0, "LDIR");  // this will choose between fast and classic

	z80_ldir_prep(page_z80_ed, 0x06, "LDIR-PREP"); // 23-4-2025 prepare for loop	
	z80_ldir_loop(page_z80_ed, 0x98, "LDIR-LOOP"); // 14-9-2024 changed from 0x10 to 0x98 (needs 3 positions)
	z80_ldir_slow(page_z80_ed, 0x20, "LDIR-SLOW");
	z80_ldir_loop_cl(page_z80_ed, 0x30, "LDIR-CL"); // ldir-classic 5-3-2025  fix C1 mode problem (not for stand-alone use)

	z80_ldir_classic(page_z80_ed, 0xB4, "LDIR-CLASSIC");  //  2-12-2025 ldir classic, for stand-alone use

	z80_lddr(page_z80_ed, 0xB8, "LDDR");  // 14-9-2024
	z80_lddr_loop(page_z80_ed, 0x10, "LDDR-LOOP");  // 14-9-2024	

	z80_cpir(page_z80_ed, 0xB1, "CPIR");  // 17-9-2024
	z80_cpdr(page_z80_ed, 0xB9, "CPDR");  // 17-9-2024	

	// more instructions needed ?

	commentline(""); commentline("------  Z80 CPU Control  ------"); commentline("");

	ins_nop(0x00, 'NOP');

	ins_nop(0x27, 'DAA');   // not implemented 18-6-2025
	z80_cpl(0x2F, 'CPL');  // complement accumulator
	z80_neg(0x44, 'NEG');  // negate accumulator
	z80_ccf(0x3F, 'CCF');  // complement carry
	ins_sec(0x37, 'SCF');  // set carry flag

	ins_in (0xDB, 'IN');  // 5-3-2024
	ins_out(0xD3, 'OUT'); // 5-3-2024   

	ins_in_ind (0x78, 'IN',reg_a,ind_c);  // 7-6-2024
	ins_out_ind(0x79, 'OUT',ind_c,reg_a); // 7-6-2024  

	ins_out_ind(0x41, 'OUT',ind_c,reg_b); // 4-11-2024  
	ins_out_ind(0x49, 'OUT',ind_c,reg_c); // 4-11-2024  
	ins_out_ind(0x51, 'OUT',ind_c,reg_d); 
	ins_out_ind(0x59, 'OUT',ind_c,reg_e);  
	ins_out_ind(0x61, 'OUT',ind_c,reg_h); 
	ins_out_ind(0x69, 'OUT',ind_c,reg_l);  				 	

	z80_hlt(page_z80, 0x76, 'HLT'); // 31-10-2024

	z80_exx(page_z80, 0xD9, 'EXX');

	z80_prefix_dd(page_z80, 0xDD, 'PREFIX IX');
	z80_prefix_fd(page_z80, 0xFD, 'PREFIX IY');
	z80_prefix_ed(page_z80, 0xED, 'PREFIX ED');
	z80_prefix_cb(page_z80, 0xCB, 'PREFIX CB');       // shift,bit,set,reset

	z80_prefix_cb(page_z80_ix, 0xCB, 'PREFIX CB'); // shift,bit,set,reset for (IX+d)
	z80_prefix_cb(page_z80_iy, 0xCB, 'PREFIX CB'); // shift,bit,set,reset for (IY+d)

	// new Z80 instructions for Isetta only

	z80_xhal(page_z80_ed, 0x77, "XHAL");  // 21-10-2024	
	z80_deczc(page_z80_ed, 0x76, "DECZ C");  // 22-10-2024	

	z80_xorz(page_z80_ix, 0x83, 'XORZ', reg_b); // 22-10-2024
	z80_xorz(page_z80_ix, 0x8B, 'XORZ', reg_c);
	z80_xorz(page_z80_ix, 0x93, 'XORZ', reg_d);	
	z80_xorz(page_z80_ix, 0x9B, 'XORZ', reg_e);
	z80_xorz(page_z80_ix, 0xA3, 'XORZ', reg_h);
	z80_xorz(page_z80_ix, 0xAB, 'XORZ', reg_l);
	z80_xorz(page_z80_ix, 0xB3, 'XORZ', ind_hl);	

	// Interrupt related

	z80_int(0x80, 'INT');  // interrupt
	z80_inrz(0x20, 'INRZ'); // interrupt, retries same instruction (does pc-2)  15-6-2024 at 0x20

	z80_im(0x46,'IM0');  // IM0 - IM2 are NOP's. In ED page. Mode is always IM1.
	z80_im(0x56,'IM1');
	z80_im(0x5E,'IM2');	
	z80_im(0x4F,'LD R,A'); // 27-4-2025  implemented as NOP
	z80_im(0x5F,'LD A,R'); // 27-4-2025	(can be used as random number)	
	z80_reti(0x4D, 'RETI', l_to_f, false);  // RETI (in ED page)

	z80_di(0xF3, 'DI');   // disable interrupt
	z80_ei(0xFB, 'EI');   // enable interrupt	

	z80_di2(0x63, 'DI2');   // disable interrupt ED 63  10-2-2025
	z80_ei2(0x6B, 'EI2');   // enable interrupt  ED 6B  10-2-2025		

	z80_ld_ia(0x47,'LD I,A')  // 2-10-2024
	z80_ld_ai(0x57,'LD A,I')  // 2-10-2024

    // The DBGC and DBGR must not be in the Z80 program. They are executed instead of CALL or RET when debugging is activated
	// Debugging can be activated on i/o port "port_out_dbg" 
	z80_dbgc(page_z80_iy, 0x20, 'DBGC CALL'); // 11-1-2025 debugger for CALL instruction
	z80_dbgr(page_z80_iy, 0x28, 'DBGR RET');  // 11-1-2025 debugger for RET instruction

	commentline("");
	commentline(instruction_counter + " opcodes generated for Z80.");
	commentline(error_m_count + " errors.");

	}  // endif generate_z80



	instruction_counter = 0; error_m_count = 0;

	if (generate_blitter == 1)
	{	

	commentline("--------------  B L I T T E R  ---------------");
	commentline("");	
	// Blitter

	// p_dst_x_l is the port number, dst_x_l is the corresponding register

	out_blit(p_dst_x_l,'p_dst_x_l', dst_x_l); // destination (screen)
	out_blit(p_dst_x_h,'p_dst_x_h', dst_x_h);	
	out_blit(p_dst_y_l,'p_dst_y_l', dst_y_l);
	out_blit(p_dst_y_h,'p_dst_y_h', dst_y_h);	

	out_blit(p_src_x_l,'p_src_x_l', src_x_l); // source
	out_blit(p_src_x_h,'p_src_x_h', src_x_h);	
	out_blit(p_src_y_l,'p_src_y_l', src_y_l);
	out_blit(p_src_y_h,'p_src_y_h', src_y_h);	
	out_blit(p_src_a_l,'p_src_a_l', src_a_l); // source addr
	out_blit(p_src_a_h,'p_src_a_h', src_a_h);	
	out_blit(p_src_a_u,'p_src_a_u', src_a_u);
	out_blit(p_src_l_l,'p_src_l_l', src_l_l); // src line len	
	out_blit(p_src_l_h,'p_src_l_h', src_l_h);	
	out_blit(p_size_x_l,'p_size_x_l', size_x_l); // area size
	out_blit(p_size_x_h,'p_size_x_h', size_x_h);	
	out_blit(p_size_y_l,'p_size_y_l', size_y_l);
	out_blit(p_size_y_h,'p_size_y_h', size_y_h);	
	out_blit(p_fill_1,'p_fill_1', fill_1); // fill
	out_blit(p_fill_2,'p_fill_2', fill_2);	

	out_blit(p_dst_x_l_new,'p_dst_x_l_new', dst_x_l); // destination (screen) new, 30-6-2025
	out_blit(p_dst_x_h_new,'p_dst_x_h_new', dst_x_h);	
	out_blit(p_dst_y_l_new,'p_dst_y_l_new', dst_y_l);
	out_blit(p_dst_y_h_new,'p_dst_y_h_new', dst_y_h);

	out_blit(p_src_a_l_new,'p_src_a_l_new', src_a_l); // source addr  30-6-2025 new
	out_blit(p_src_a_h_new,'p_src_a_h_new', src_a_h);	
	out_blit(p_src_a_u_new,'p_src_a_u_new', src_a_u);
	out_blit(p_src_l_l_new,'p_src_l_l_new', src_l_l); // src line len	
	out_blit(p_src_l_h_new,'p_src_l_h_new', src_l_h);		


	out_blit_start(port_blitter,'BLIT'); // 22-11-2024

	z80_txtget(0x6C,'TXTGET');  // 27-04-2025  TEXTGET  ED 6C (not used yet 30-9-2025)

	z80_rowsel(0x5C,'ROWSEL');  // 28-4-2025 ROW SELECT  ED 5C  (not used yet 30-9-2026)

	txtrow(0x40,"TXTROW 0"); // 1-5-2025 add txtrow 0
	txtrow(0x44,"TXTROW 2"); // 28-4-2025 row of a character, 2 pixels, in blitter page  (not used yet 30-9-2026)
	txtrow(0x48,"TXTROW 4");
	txtrow(0x4C,"TXTROW 6");
	txtrow(0x50,"TXTROW 8");	

	col4to16(0x54,"COL4TO16"); // 4-5-2025 convert 4-color to 16-color for SymbOs  ED 54

	// 11-1-2025
	
	blit_actions(0x00,"N"); // copycnv , copy and convert color
	blit_actions(0x0B,"R"); // reverse-x-copy (not functional 30-9-2025)
	blit_actions(0x02,"2"); // copy 2 bpp to 4 bpp (not fully functional 30-9-2025)
	blit_actions(0x04,"S"); // skip: copy, convert color, skip transparent pixels	
	blit_actions(0x06,"M"); // skip 2 bpp to 4 bpp (not fully functional 30-9-2025)
	blit_actions(0x08,"C"); // copy, without color conversion or transparency. Here 20-3-2025	
	blit_actions(0x01,"V"); // save
	blit_actions(0x09,"T"); // text
	// blit_actions(0x2D,"F"); // fill  
	// blit_actions(0x2E,"X"); // xor-fill	
	blit_actions(0x0D,"F"); // fill    // 12-1-2025  no 0x20 in opcode here !
	blit_actions(0x0E,"X"); // xor-fill	

	blit_newline(opc_inc_all,"NL_INC_ALL");
	blit_newline(opc_dec_all,"NL_DEC_ALL");
	blit_newline(opc_inc_dst,"NL_INC_DST");	
	blit_newline(opc_fast_inc,"NL_FAST_INC");  // 25-4-2025

	commentline("");
	commentline(instruction_counter + " opcodes generated for Blitter.");
	commentline(error_m_count + " errors.");

	} // endif generate_blitter



	instruction_counter = 0; error_m_count = 0;
	
	commentline("");	
	commentline("--------------  S O U N D    G E N E R A T O R  ---------------");
	commentline("");	

	out_psg_regsel (port_out_psg_reg, "PSG REGSEL"); // 0x40
	out_psg_data   (port_out_psg_data,"PSG DATA");   // 0x41
								// 0x42 reserved for more PSG modes
	out_sound_mode (port_out_sound_mode,"Sound Mode");   // 0x43	

	// The following registers can only be written through the REGSEL / DATA output ports.
	// For exact description, see AY-3-8910 datasheet. The PSG is clocked with 2.00 MHz.
	out_psg_reg(0x30,1,"PSG ch1 period lsb");
	out_psg_reg(0x31,1,"PSG ch1 period msb"); // bit 0-3 only
	out_psg_reg(0x32,2,"PSG ch2 period lsb");
	out_psg_reg(0x33,2,"PSG ch2 period msb"); // bit 0-3 only
	out_psg_reg(0x34,3,"PSG ch3 period lsb");
	out_psg_reg(0x35,3,"PSG ch3 period msb"); // bit 0-3 only
	out_psg_reg(0x36,4,"PSG noise period");   // bit 0-4 only
	out_psg_reg(0x37,0,"PSG enable/");
	out_psg_reg(0x38,1,"PSG ch1 amplitude"); // bit0-3 amplitude, bit4: use-envelope
	out_psg_reg(0x39,2,"PSG ch2 amplitude"); // bit0-3 amplitude, bit4: use-envelope
	out_psg_reg(0x3A,3,"PSG ch3 amplitude"); // bit0-3 amplitude, bit4: use-envelope
	out_psg_reg(0x3B,1,"PSG envelope period lsb");
	out_psg_reg(0x3C,1,"PSG envelope period msb");
	out_psg_reg(0x3D,1,"PSG envelope cycle");  // bit 0-3 only
	out_psg_reg(0x3E,0,"PSG unused");
	out_psg_reg(0x3F,0,"PSG unused");	


	out_psg_lsb (0x47,"PSG LSB"); // 25-5-2025
	out_psg_msb (0x57,"PSG MSB");	
	out_psg_noisefreq (0x59,"PSG NOISEFREQ"); // 26-5-2025	

	i=0;
	while (i<= 15)
	  { psg_square_sample(i);  // 18-5-2025
	    i++;
	  }
	i=0;
	while (i<= 15)
	  { psg_noise_samples(i);  // 26-5-2025
	    i++;
	  }

	psg_functions(); // 19-5-2025
	

	commentline("");
	commentline(instruction_counter + " opcodes generated for sound generator.");
	commentline(error_m_count + " errors.");
	instruction_counter = 0; error_m_count = 0;

	commentline_end();  // 15-8-2025  (after build-reset, there is another commentline_end)

} // build_microcode end



function build_reset() {
	instruction_counter = 0; error_m_count = 0;	
	commentline("");	
	commentline("--------------    I S E T T A    R E S E T    ---------------");
	commentline("");	

	isetta_reset(page_reset, 0x00, 'RESET');
		
	isetta_tbl1(page_z80_ix, 0x01, 'TBL1'); // 30-10-2024

	init_values(page_reset, 'VAL'); // 6-2-2024 init val0 - val63

	isetta_go_proc(page_reset, ISA_6502, 'G6502');  // jp back to 6502 after I/O instruction
	isetta_go_proc(page_reset, ISA_Z80, 'GZ80');  // jp back to Z80 after I/O instruction


	isetta_go(page_reset, 0x07, 'GO');  // jp to currently selected processor (defined in reg_isa)

	// I/O port definitions

	/*
	port_out_console
	port_out_spidata
	port_in_spidata  
	port_in_hwversion
	port_in_mcversion // microcode version
	port_out_wrbank0 // bank0-7
	port_in_rdbank4
	port_io_reg_isa // write to named register. in bank 6 and 7, reg0-7, hi = 0/1 (32 different ones)
	port_io_reg_vga_ptl  // 29-4-2024
	port_io_reg_vga_pth
	*/

	// read or write from/to RAM-based registers
	inout_reg(port_io_reg_isa, reg_isa); // set this to isa_6502 or isa_z80 or....
	inout_reg(port_out_system, reg_os); // set/read system specific behaviour. default is 0.
	inout_reg(port_out_dbg, reg_dbg); // 11-1-2025 set/read debug register	

	out_isa(port_out_isa_6502);  // set processor to 6502
	out_isa(port_out_isa_Z80);  // set processor to Z80

	inout_reg(port_io_reg_vga_ptl, reg_vga_ptl);  // 29-4-2024
	inout_reg(port_io_reg_vga_pth, reg_vga_pth);
	inout_reg(port_io_reg_vga_base,reg_vga_base); // 29-4-2024 at end of frame, vga_pt is loaded with vga_base	


    in_gen_input(port_in_gen_input);  // 29-5-2024 general input port

	in_const(port_in_config, 0); // 14-12-2024 read the HW configuration here. For now, always zero.

	// 2-1-2024 make microcode date stamp

	in_const(port_in_microcode_year, thisyear - 2000);
	in_const(port_in_microcode_month, thismonth);
	in_const(port_in_microcode_day, thisday);

	in_const(port_in_bnk1_free, 0x21);			

// for writing/reading ACC to/from another memory bank, address in HL

    inout_bank(0xF0,bank0); // added 13-11-2024
    inout_bank(0xF1,bank1);
    inout_bank(0xF2,bank2);
	inout_bank(0xF3,bank3);
    inout_bank(0xF4,bank4); // bnk 4-7 won't work any more, 13-11-2024
	inout_bank(0xF5,bank5);
	inout_bank(0xF6,bank6);
	inout_bank(0xF7,bank7);	

	ins_out_sbnk(port_out_sbnk,'SBNK',nop,nop);  // 18-3-2025 set bank number

	ins_out_sbnkjp(port_out_sbnkjp,'SBNKJP',nop,nop);  // 25-11-2025 set bank number and jump

	ins_out_wbnk(port_out_wbnk,'WBNK',nop,nop); // 26-11-2025 set bank, A = 0-15, using bit7 and bit6 from H
	ins_in_rbt(port_in_rbt,'RBT',nop,nop); // read from selected bank to B
	ins_out_wbt(port_out_wbt,'WBT',nop,nop)	// write C to selected bank

	in_kb(port_in_scancode);

	out_tx(port_out_tx);	

	out_shutdn(port_out_shutdn); // 30-6-2025

	out_sound_direct(port_out_sound); // write to sound register (when no VDU used)

	// instructions for KB / TX device driver

	io_kb_startbit(KB_STATE_WAIT);
	io_kb_startbit_end(KB_STATE_WAITE);
	io_kb_databit(KB_STATE_BIT0);
	io_kb_databit_end(KB_STATE_BIT0E);
	io_kb_databit(KB_STATE_BIT1);
	io_kb_databit_end(KB_STATE_BIT1E);
	io_kb_databit(KB_STATE_BIT2);
	io_kb_databit_end(KB_STATE_BIT2E);
	io_kb_databit(KB_STATE_BIT3);
	io_kb_databit_end(KB_STATE_BIT3E);
	io_kb_databit(KB_STATE_BIT4);
	io_kb_databit_end(KB_STATE_BIT4E);
	io_kb_databit(KB_STATE_BIT5);
	io_kb_databit_end(KB_STATE_BIT5E);
	io_kb_databit(KB_STATE_BIT6);
	io_kb_databit_end(KB_STATE_BIT6E);
	io_kb_databit(KB_STATE_BIT7);
	io_kb_databit_end_last(KB_STATE_BIT7E);
	// The data was sent with the highest bit (bit7) first !
	io_kb_paritybit(KB_STATE_PAR);
	io_kb_paritybit_end(KB_STATE_PARE);

	// Instructions for mouse driver

	io_mouse_startbit(MOUSE_STATE_WAIT);
	io_mouse_startbit_end(MOUSE_STATE_WAITE);
	io_mouse_databit(MOUSE_STATE_BIT0);
	io_mouse_databit_end(MOUSE_STATE_BIT0E);
	io_mouse_databit(MOUSE_STATE_BIT1);
	io_mouse_databit_end(MOUSE_STATE_BIT1E);
	io_mouse_databit(MOUSE_STATE_BIT2);
	io_mouse_databit_end(MOUSE_STATE_BIT2E);
	io_mouse_databit(MOUSE_STATE_BIT3);
	io_mouse_databit_end(MOUSE_STATE_BIT3E);
	io_mouse_databit(MOUSE_STATE_BIT4);
	io_mouse_databit_end(MOUSE_STATE_BIT4E);
	io_mouse_databit(MOUSE_STATE_BIT5);
	io_mouse_databit_end(MOUSE_STATE_BIT5E);
	io_mouse_databit(MOUSE_STATE_BIT6);
	io_mouse_databit_end(MOUSE_STATE_BIT6E);
	io_mouse_databit(MOUSE_STATE_BIT7);
	io_mouse_databit_end_last(MOUSE_STATE_BIT7E);
	// The data was sent with the highest bit (bit7) first !
	io_mouse_paritybit(MOUSE_STATE_PAR);
	io_mouse_paritybit_end(MOUSE_STATE_PARE);

	in_mouse(port_in_mouse);

	// Instructions for sound device driver

	io_wr_sound(SOUND_STATE_IDLE); // psg sound
	io_wr_sound(SOUND_STATE_ZX); // 1-9-2025 zx-spectrum sound

	// I/O ports for SPI bus transactions

 	// 22-10-2024
	out_spi_start(port_spi1_start);  // 0x32 Start SPI on device spi1
	out_spi_start(port_spi2_start);  // 0x33 Start SPI on device spi2
	out_spi_wr(port_spi_out);   // 0x37 Output one byte to SPI bus
	out_spi_wr(port_spi2_out);   // 0x3B Output one byte to SPI2 bus  6-4-2025
	in_spi_rd(port_spi_in);     // 0x3A Input one byte from prev selected SPI device
	in_spi_rd(port_spi2_in);    // 0x37 Input one byte from prev selected SPI2 device, read bit before clock
	in_spi_rd(port_spi2_in_fast);    // 0x47 	
	in_spi_rd(port_spi_in_bit);     // 0x3E Input one bit from prev selected SPI device	 30-3-2025
	in_spi_state(port_spi_state);   // 0x3C Input. returns Z if SPI busy. 10-2-2025
	out_spi_wr(port_spi_out_bit);   // 0x3D Output single bit to SPI bus, slow  30-3-2025
	out_spi_idle(port_spi_idle); // 0x3F Close SPI transaction	

	// I/O ports for messages to the keyboard 27-5-2024 and to mouse 27-11-2024

	out_bit(port_out_sw_exx);	    
	out_bit(port_out_sw_vdu_n);  // 27-11-2024
	out_bit(port_out_setup);	 // 27-11-2024
	out_bit(port_out_sound_imm); // 21-12-2024

	//out_bit(port_out_sw_wr_sound_n); // 4-2-2026 for LED blinking during startup, unused

	// I/O ports for ZX Spectrum  7-6-2024

	inout_zx_spectrum(port_io_zx_spectrum); // 7-6-2024
	in_zx_joystick(port_io_zx_joystick) ; // 15-6-2024

	// Instructions for video device driver

	video_init();     // 12-5-2024

	// Instructions for bankswitching  4-11-2024

	// The ins_bsw can not be used on it's own. Always use OUT (C),reg that will jp to one of these.

	ins_bsw(0x00,'BC0',0);
	ins_bsw(0x01,'BC1',1);
	ins_bsw(0x02,'BC2',2);
	ins_bsw(0x03,'BC3',3);	
	ins_bsw(0x04,'BC4',4);
	ins_bsw(0x05,'BC5',5);
	ins_bsw(0x06,'BC6',6);
	ins_bsw(0x07,'BC7',7);				

	commentline("");
	commentline(instruction_counter + " opcodes generated for Isetta reset and device drivers.");
	commentline(error_m_count + " errors.");

	statistics();

	commentline_end();  // 15-8-2025 
}


// try: https://www.asm80.com/   assembler voor z80/6502
